Many mainstream frameworks use reflection technology. For example, the ssh framework uses two technologies: xml as configuration file + reflection technology.
Class packages related to reflection.
java.lang.reflect.*; and java.lang.Class;
All types in Java (including basic types) correspond to a Class object, and this Class is java.lang.Class. That is, each type has a Class object corresponding to it in Class. Class has no public constructor. Note that it’s not that there is no public access.
How to get Class object
Copy the code code as follows:
.For each object.getCalss(), you can get the corresponding Class.
.Class.forName(String), the writing method of String: package name.class name.The object corresponding to the package name.class name will be created. Note: 1.2 only applies to reference types.
.For basic types: encapsulation class. TYPE represents the Class object of the corresponding basic type. Integer.TYPE corresponds to the Class object of int. Note: 3 only applies to basic types.
.Type, Class. <Type 4 is universal.>
Of the four methods above, only method 2 is dynamic. Just change a package. It has dynamic potential. Therefore, if you want to truly embody dynamic programming, you can only use method 2.
There is only one Class object of each type, that is, they have only one address, but different types are different.
So the following print results are all true.
Copy the code code as follows:
//Pair and reference types
Class c1 = "".getClass();
Class c2 = Class.forName("java.lang.String");
Class c3 = String.class;
System.out.println(c1 ==c2);//true
//For basic types
Class num1 = Integer.TYPE;
Class num2 = int.class;
System.out.println(num1 == num2);//true
Reflection to obtain related methods of members in a class
[Get structure <according to parameter type>] (generally used without declared)
Copy the code code as follows:
Constructor<T> getConstructor(Class<?>... parameterTypes)
Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.
Constructor<?>[] getConstructors()
Returns an array containing Constructor objects that reflect all public constructors of the class represented by this Class object.
Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
Returns a Constructor object that reflects the specified constructor method for the class or interface represented by this Class object.
Constructor<?>[] getDeclaredConstructors()
Returns an array of Constructor objects that reflect all constructor methods declared by the class represented by this Class object.
[Get attribute <according to attribute name>] (usually used with declared, because attributes are generally private)
Copy the code code as follows:
Field getField(String name)
Returns a Field object that reflects the specified public member fields of the class or interface represented by this Class object.
Field[] getFields()
Returns an array containing Field objects that reflect all accessible public fields of the class or interface represented by this Class object.
Field getDeclaredField(String name)
Returns a Field object that reflects the specified declared field of the class or interface represented by this Class object.
Field[] getDeclaredFields()
Returns an array of Field objects that reflect all fields declared by the class or interface represented by this Class object.
[Getting method <method name plus parameter type>] (usually used without declared)
Copy the code code as follows:
Method getMethod(String name, Class<?>... parameterTypes)
Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.
Method[] getMethods()
Returns an array containing Method objects that reflect the public members of the class or interface represented by this Class object (including those declared by that class or interface and those inherited from superclasses and superinterfaces) method.
Method getDeclaredMethod(String name, Class<?>... parameterTypes)
Returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.
Method[] getDeclaredMethods()
Returns an array of Method objects that reflect all methods declared by the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding inherited methods.
T newInstance()
Creates a new instance of the class represented by this Class object. <new Instance() can dynamically create objects>
String toString()
Convert object to string.
Notice: newInstance() calls a parameterless constructor. If the class does not have a parameterless constructor, newInstance() will generate an exception.
Declared methods support privateness, but do not support inheritance. Undeclared methods support inheritance, but do not support privateness, and can only take out public things.
Therefore, properties are generally declared with declaration, because properties are generally private, methods are generally obtained without declaration, and constructors are generally obtained without declaration.
Instance simulation reflection obtains relevant properties and methods in the class
Using reflection to assign values to properties
Methods in Field
Object get(Object obj)
Returns the value of the field represented by this Field on the specified object.
Field f = c.getXXField(property name);
value = f.get(object);
void set(Object obj, Object value)
Sets the field represented by this Field object on the specified object variable to the specified new value.
f.set(object, value);
Class<?> getType()
Returns a Class object that identifies the declared type of the field represented by this Field object.
Used to get the type of attribute (returns Class object).
Copy the code code as follows:
Class c = Student.class;
Object obj = c.newInstance(); //Create an object of Student class
Field f = c.getDeclaredField("name"); //Get the name attribute
f.setAccessible(true); //Set private access.
f.set(obj, "zhangsan");
System.out.println(f.get(obj)); //Get the value of obj's name attribute.
Using reflection to call constructs The actual call to the constructor is when the newInstance() method is called.
Copy the code code as follows:
Class c = Class.forName("com.clazz.reflect.Student");
Constructor con = c.getConstructor(); //No construction is performed,
Object cObj = c.getConstructor().newInstance();//Call the parameterless constructor
Constructor conAll = c.getConstructor(int.class,String.class,int.class);
Object caobj = conAll.newInstance(1001,"zjamgs",234235);//Call the constructor with parameters.
System.out.println(caobj); //Print output
Calling methods using reflection Object.Method name(value 1,2,3);
Method m = c.getMethoed(method name, parameter type...);
m.invoke (object, method call parameters) If the formal parameter required by the underlying method is 0, the length of the provided args array can be 0 or null.
Copy the code code as follows:
Class c = Class.forName("com.clazz.reflect.Student");
Object obj = c.newInstance(); //Create a Sutdent object.
Method msetName = c.getMethod("setName", String.class);//obj does not need to convert type
msetName.invoke(obj, "zhangsan");//Call method setName and pass parameters.
Method msetId = c.getMethod("setId", int.class);
msetId.invoke(obj, 409090202);
System.out.println(obj);
Reflection application examples Entity class
Copy the code code as follows:
package org.dennisit.reflect.entity;
import java.io.Serializable;
/**
*
*User.java
*
* @version: 1.1
*
* @author: Su Ruonian<a href="mailto:
[email protected]">Send email</a>
*
* @since: 1.0 Creation time: 2013-2-26 01:43:56 pm
*
* TODO: class User.java is used for ...
*
*/
public class User implements Serializable{
private String test;
public void execute(String name,int age){
System.out.println("name=" + name + ",age=" + age);
}
}
Reflection test class
Copy the code code as follows:
package org.dennisit.reflect.main;
import java.lang.reflect.Field;
/**
*
* ReflectEx.java
*
* @version: 1.1
*
* @author: Su Ruonian<a href="mailto:
[email protected]">Send email</a>
*
* @since: 1.0 Creation time: 2013-2-26 01:46:00 pm
*
* TODO: class ReflectEx.java is used for ...
*
*/
public class ReflectEx {
public static void main(String[] args)throws Exception {
Class cls = Class.forName("org.dennisit.reflect.entity.User");
Object obj = cls.newInstance(); //Create User object
Field f = cls.getDeclaredField("test"); //Get the test attribute
f.setAccessible(true); //Open access permissions for private attribute test
f.set(obj, "zhangsan"); //Copy again for test
System.out.println(f.get(obj)); //Get the test attribute value of obj
//Get the method based on the method name execute
java.lang.reflect.Method m = cls.getMethod("execute", String.class, int.class);
m.invoke(obj, "dennisit",23); //Call execute method
}
}
Operation effect
Copy the code code as follows:
zhangsan
name=dennisit,age=23
Example of writing a reflective dynamic instantiation class
Copy the code code as follows:
package org.dennisit.reflect.main;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;
/**
*
* DynamicReflect.java
*
* @version: 1.1
*
* @author: Su Ruonian<a href="mailto:
[email protected]">Send email</a>
*
* @since: 1.0 Creation time: 2013-2-26 01:58:12 pm
*
* TODO: Example of dynamic instantiation using reflection
*
*/
public class DynamicReflect {
public static Object getInstance(String className,Map<String,Object> map)throws Exception{
Class c = Class.forName(className);
Object obj = c.newInstance(); //Object object
Set<String> keys = map.keySet(); //Get all corresponding attributes
Field[] fAll = c.getDeclaredFields(); //Get all properties in the class
for(int i=0;i<fAll.length;i++){
for(String key:keys){ //Loop matching
if(fAll[i].getName().equals(key)){ //If the attribute passed in by the user matches the attribute name in the obtained class
Field f = c.getDeclaredField(key);//Get this attribute
//Construct the setXxx() method name
String methodName = "set" + key.substring(0,1).toUpperCase()+key.substring(1);
Method method = c.getMethod(methodName, f.getType());//Get the corresponding method based on the constructed user name
method.invoke(obj, map.get(key));//Method call
}else{
continue;
}
}
}
return obj;
}
}
Next we test the dynamic reflection instantiation example we wrote
Entity class
Copy the code code as follows:
package org.dennisit.reflect.entity;
import java.io.Serializable;
/**
*
*User.java
*
* @version: 1.1
*
* @author: Su Ruonian<a href="mailto:
[email protected]">Send email</a>
*
* @since: 1.0 Creation time: 2013-2-26 01:43:56 pm
*
* TODO: Entity class
*
*/
public class User implements Serializable{
private String name;
private int age;
private String email;
public User() { //Must have no parameter constructor
}
//getter() and setter()
}
Main test class
Copy the code code as follows:
package org.dennisit.reflect.main;
import java.util.HashMap;
import java.util.Map;
import org.dennisit.reflect.entity.User;
/**
*
* ReflectEx.java
*
* @version: 1.1
*
* @author: Su Ruonian<a href="mailto:
[email protected]">Send email</a>
*
* @since: 1.0 Creation time: 2013-2-26 01:46:00 pm
*
* TODO: class ReflectEx.java is used for ...
*
*/
public class ReflectEx {
public static void main(String[] args)throws Exception {
Class cls = Class.forName("org.dennisit.reflect.entity.User");
String className = "org.dennisit.reflect.entity.User";
Map<String,Object> map = new HashMap<String, Object>();
map.put("name", "dennisit");
map.put("age", 22);
map.put("email", "[email protected]");
User user = (User)DynamicReflect.getInstance(className, map);
System.out.println(user.getName() + "," + user.getAge() + "," + user.getEmail());
}
}
Program running results
Copy the code code as follows: