Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Java Reflection
1. Hamid Ghorbani Java Advanced Tutorial(Reflection) https://ir.linkedin.com/in/ghorbanihamid
Java Reflection :
Java Reflection provides ability to inspect and modify the runtime behavior of application. Using java reflection we
can inspect a class, interface, enum, get their structure, methods and fields information at runtime even though
class is not accessible at compile time. We can also use reflection to instantiate an object, invoke it’s methods,
change field values. Some of the frameworks that use java reflection are, Junit, Spring, Tomcat , Eclipse, Struts,
Hibernate.
Where it is used:
o IDE (Integrated Development Environment) e.g. Eclipse, MyEclipse, NetBeans etc.
o Debugger
o Test Tools etc.
We should not use reflection in normal programming where we already have access to the classes and interfaces
because of following drawbacks:
Poor Performance – Since java reflection resolve the types dynamically, it involves processing like
scanning the classpath to find the class to load, causing slow performance.
Security Restrictions – Reflection requires runtime permissions that might not be available for system
running under security manager. This can cause you application to fail at runtime because of security
manager.
Security Issues – Using reflection we can access part of code that we are not supposed to access, for
example we can access private fields of a class and change it’s value. This can be a serious security threat
and cause your application to behave abnormally.
High Maintenance – Reflection code is hard to understand and debug, also any issues with the code can’t
be found at compile time because the classes might not be available, making it less flexible and hard to
maintain.
Getting Class Object:
Before you can do any inspection on a class you need to obtain its java.lang.Class object. All types in Java
including the primitive types (int, long, float etc.) and arrays have an associated Class object.
2. Hamid Ghorbani Java Advanced Tutorial(Reflection) https://ir.linkedin.com/in/ghorbanihamid
There are 3 ways to get the instance of Class class. They are as follows:
o the .class syntax
o getClass() method of Object class
o forName() method of Class class
1) The .class syntax:
If a type is available but there is no instance then it is possible to obtain a Class by appending
".class" to the name of the type.It can be used for primitive data type also.
package com.behsazan;
class TestClass {.… }
Class aClass = TestClass.class;
String className = aClass.getName();
// for primitive Types
Class aClass = boolean.class;
Class bClass = int.class;
String className = aClass.getName();
2) getClass() method:
It should be used if you know the type.
TestClass testClassObject =new TestClass();
Class aClass = testClassObject.getClass();
boolean myVar;
Class aClass = myVar.getClass(); // compile-time error
3) forName() method:
If you don't know the name at compile time, but have the class name as a string at runtime,
you can do like this:
Class aClass = Class.forName("com.behsazan.TestClass");
Superclass
From the Class object you can access the superclass of the class. The superclass class object is a Class object
like any other, so you can continue doing class reflection on that too. Here is how:
Class superclass = aClass.getSuperclass();
3. Hamid Ghorbani Java Advanced Tutorial(Reflection) https://ir.linkedin.com/in/ghorbanihamid
Constructors
You can access the constructors of a class like this:
Constructor[] constructors = aClass.getConstructors();
Methods
You can access the methods of a class like this:
Method[] method = aClass.getMethods(); // get List of methods
Method[] method = aClass.getDeclaredMethods();
Method method = aClass.getMethod("methodName", methodParams);
Method method = aClass.getDeclaredMethod("methodName", methodParams);
getMethod VS getDeclaredMethod:
تفاوتgetMethodﺑاgetDeclaredMethodتاﺑع در كه كه است اين درgetMethodدر متد دنبال ﺑه ،نكند پيدا را متد جاري كﻼس در اگر
كﻼسsuper.گردد مي آن
Fields
You can access the fields (member variables) of a class like this:
Field[] fields = aClass.getFields();
Field[] fields = aClass.getDeclaredFields();
Field field = aClass. getField(("fieldName");
Field field = aClass. getDeclaredField(("fieldName");
Package Info
You can obtain information about the package from a Class object like this:
Class aClass = ... //obtain Class object. See prev. section
Package package = aClass.getPackage();
4. Hamid Ghorbani Java Advanced Tutorial(Reflection) https://ir.linkedin.com/in/ghorbanihamid
Modifiers
The class modifiers are the keywords "public", "private", "static" etc. The modifiers are packed into an int
where each modifier is a flag bit that is either set or cleared. You can obtain the class modifiers like this:
Class aClass = ... //obtain Class object
int modifiers = aClass.getModifiers();
You can check the modifiers using these methods in the class java.lang.reflect.Modifier:
Modifier.isAbstract(int modifiers)
Modifier.isFinal(int modifiers)
Modifier.isInterface(int modifiers)
Modifier.isNative(int modifiers)
Modifier.isPrivate(int modifiers)
Modifier.isProtected(int modifiers)
Modifier.isPublic(int modifiers)
Modifier.isStatic(int modifiers)
Modifier.isStrict(int modifiers)
Modifier.isSynchronized(int modifiers)
Modifier.isTransient(int modifiers)
Modifier.isVolatile(int modifiers
Example:
Public class SimpleClass{
public void method1 (){
System.out.println("method1() was called!");
}
public void method2 (String tempStr){
System.out.println("method2() was called!" + tempStr);
}
public void method3 (int tempInt){
System.out.println("method3() was called!" + tempInt);
5. Hamid Ghorbani Java Advanced Tutorial(Reflection) https://ir.linkedin.com/in/ghorbanihamid
}
}
public static void main(String args[]) {
//no paramater
Class noparams[] = {};
//String parameter
Class[] paramString = new Class[1];
paramString[0] = String.class;
//int parameter
Class[] paramInt = new Class[1];
paramInt[0] = Integer.TYPE;
try {
Class tempClass = Class.forName("com.behsazan.SimpleClass");
Object obj = tempClass.newInstance();
//call the method1 method
Method method = cls.getDeclaredMethod("method1", noparams);
method.invoke(obj, null);
//call the method2 with String Inputs
Method method = cls.getDeclaredMethod("method2", paramString);
method.invoke(obj, new String("inputParams"));
//call the method3 with Interger Inputs
Method method = cls.getDeclaredMethod("method3", paramInt);
method.invoke(obj, 1234);
} catch (ClassNotFoundException ee) {
System.out.println("Couldn't find class 'SimpleClass'");
System.exit(1);
}
}
TYPE Field for Primitive Type Wrappers
The .class syntax is a more convenient and the preferred way to obtain the Class for a primitive type;
however there is another way to acquire the Class. Each of the primitive types and void has a wrapper class
in java.lang that is used for boxing of primitive types to reference types. Each wrapper class contains a field
named TYPE which is equal to the Class for the primitive type being wrapped.
Class c = Double.TYPE;
is identical to
Class c = double.class.
Class c = Void.TYPE;
is identical to
Class c = void.class.
6. Hamid Ghorbani Java Advanced Tutorial(Reflection) https://ir.linkedin.com/in/ghorbanihamid
Reflection – Arrays:
Working with arrays via Java Reflection is done using the java.lang.reflect.Array class.
Creating Arrays
Creating arrays via Java Reflection is done using the java.lang.reflect.Array class.
1. // This code sample creates an array of type int (int.class parameter) and size of 3
int[] intArray = (int[]) Array.newInstance(int.class, 3);
2. int dimensions[] = {3, 4};
int twoDimensionalIntArray[][] = (int[][])Array.newInstance(int.class, dimensions);
Accessing Arrays
int[] intArray = (int[]) Array.newInstance(int.class, 3);
Array.set(intArray, 0, 123);
Array.set(intArray, 1, 456);
Array.set(intArray, 2, 789);
System.out.println("intArray size = " + Array. getLength(intArray));
System.out.println("intArray[0] = " + Array.get(intArray, 0));
System.out.println("intArray[2] = " + Array.get(intArray, 2));
Sample Result:
intArray size = 3
intArray[0] = 123
intArray[2] = 789
Obtaining the Class Object of an Array
1. with .class Syntax:
Class intArrayClass = int[].class;
Class doubleArrayClass = double[].class;
Class stringTwoDimensionalArrayClass = String[][].class;
2. Using Class.forName:
Class intArray = Class.forName("[I"); // identical to int[].class
7. Hamid Ghorbani Java Advanced Tutorial(Reflection) https://ir.linkedin.com/in/ghorbanihamid
Class cDoubleArray = Class.forName("[D"); // identical to double[].class
Class cStringArray = Class.forName("[[Ljava.lang.String;"); // identical to String[][].class
Obtaining the Component Type of an Array
Once you have obtained the Class object for an array you can access its component type via the
Class.getComponentType() method.
The component type is the type of the items in the array. For instance, the component type of an int[] array
is the int.class Class object. The component type of a String[] array is the java.lang.String Class object.
Example1:
String[] strings = new String[3];
Class stringArrayClass = strings.getClass();
Class stringArrayComponentType = stringArrayClass.getComponentType();
System.out.println(stringArrayComponentType); // prints : "java.lang.String"
Example2:
int[] object = {1,2,3};
Class aClass = object.getClass();
if (aClass.isArray()) {
Class elementType = aClass.getComponentType();
System.out.println("Array of: " + elementType); // prints : Array of: int
}
Example3:
import java.lang.reflect.Array;
public class ReflectionHelloWorld {
public static void main(String[] args) {
int[] intArray = { 1, 2, 3, 4, 5 };
int[] newIntArray = (int[]) changeArraySize(intArray, 10);
print(newIntArray);
String[] atr = { "a", "b", "c", "d", "e" };
String[] str1 = (String[]) changeArraySize(atr, 10);
print(str1);
}
// change array size
public static Object changeArraySize(Object obj, int len) {
8. Hamid Ghorbani Java Advanced Tutorial(Reflection) https://ir.linkedin.com/in/ghorbanihamid
Class<?> arr = obj.getClass().getComponentType();
Object newArray = Array.newInstance(arr, len);
//do array copy
int co = Array.getLength(obj);
System.arraycopy(obj, 0, newArray, 0, co);
return newArray;
}
// print
public static void print(Object obj) {
Class<?> c = obj.getClass();
if (!c.isArray()) {
return;
}
System.out.println("nArray length: " + Array.getLength(obj));
for (int i = 0; i < Array.getLength(obj); i++) {
System.out.print(Array.get(obj, i) + " ");
}
}
}
reflection & Generics:
public class MyGenericClass<T extends Number> {
private String name = "Default Name";
private int age;
private T counter;
public MyGenericClass(String tempVar) {
this.name = tempVar;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public T getCounter() {
return counter;
}
public void setCounter(T counter) {