Summary of java reflection

Keywords: Java Attribute

1.Class class
Any class is an instance object of Class, which has three representations
// The first expression - > actually tells us that any class has an implicit static member variable class (that is, the class type of this class).
Class c1 = User.class;
// The second expression already knows that objects of this class pass through the getClass method
User user = new User();
Class c2 = user.getClass();
Official website c1, C2 denotes the class type of User class
* Everything is an object.
* Class is also an object, an instance object of Class class
* This object is what we call the class type of this class.
// Whether c1 or c2 represents the class type of the User class, a class can only be an instance object of the Class class.
System.out.println(c1 == c2);===true
// The third way of expression
Class c3 = Class.forName("com.wx.model.User");
System.out.println(c2==c3);===true
From the above, we know that each class has and only has one class type of this class.
// We can create an instance of the class entirely by its class type - > create an instance object of User by c1 or c2 or c3
User user = (User)c1.newInstance(); // Need a parameterized construction method
Class.forName("full name of class")
It not only represents the class type of the class, but also represents the dynamically loaded class.
Distinguishing compiler from runtime load class is static load class and runtime load class is dynamic load class
* When compiling, a class declares that several objects must be created. If it is not used, it will make an error. That is, when new creates an object, it loads the class statically, so it loads all possible classes at compiling time. All of them have methods to dynamically load classes to solve this problem.
class Student implements People{
start(){syso("Teacher");}
}
class Teacherimplements People{
start(){syso("Teacher");}
}
interface People{
public vaid start();
}
class Test{
public static void main(String[] agrs){
Class c = Class.forName(args[0]);//Dynamic loading of classes, loading at runtime
People p = (People)c.newInstance();//Create this class object by class type
p.start();
}
}




* Basic data types
public class ClassDemo2 {
	public static void main(String[] args) {
		Class c1 = int.class;//Class type of int
		Class c2 = String.class;//String class type String class bytecode (invented by myself)
		Class c3 = double.class;
		Class c4 = Double.class;
		Class c5 = void.class;
		
		System.out.println(c1.getName());
		System.out.println(c2.getName());
		System.out.println(c2.getSimpleName());//The name of a class that does not contain a package name
		System.out.println(c5.getName());
	}
}


Result:
int
java.lang.String
String
void
* Reflection of class
public class ClassUtil {
/**
 * Print class information, including class member functions, member variables (get member functions only)
  * 1.Acquisition method
 * @param obj Information about the class to which the object belongs
 */
public static void printClassMethodMessage(Object obj){ /*   String s = "hello";  s String type object  */
//To get information about a class, you first need to get the class type of the class.
Class c = obj.getClass();//The second method passes the object c of which subclass is the class type of that subclass.
//Get the name of the class
System.out.println("The name of the class is:"+c.getName());	//The name of the class is: java.lang.String
/*
 * Method Class, Method Object
 * A member method is a Method object
 * getMethods()The method takes all public functions, including those inherited from the parent class.
 * getDeclaredMethods()Gets all the methods declared by the class itself, regardless of access rights
 */
Method[] ms = c.getMethods();//c.getDeclaredMethods()
for(int i = 0; i < ms.length;i++){
//Get the class type of the return value type of the method
Class returnType = ms[i].getReturnType();
System.out.print(returnType.getName()+" ");		//The return type is called bollean
//Get the name of the method
System.out.print(ms[i].getName()+"(");			//equals(
//Get the parameter type - > and get an array of class types for the type of the parameter list
Class[] paramTypes = ms[i].getParameterTypes();
for (Class class1 : paramTypes) {
System.out.print(class1.getName()+",");		//java.lang.Object,
}
System.out.println(")");						//)
}
}
    /**
     *  2.Getting information about member variables
     * @param obj
     */
public static void printFieldMessage(Object obj) {
Class c = obj.getClass();
/*
 * Membership variables are also objects
 * java.lang.reflect.Field
 * Field Classes encapsulate operations on member variables
 * getFields()Method gets information about all public member variables
 * getDeclaredFields Gets information about the member variables declared by the class itself
 */
//Field[] fs = c.getFields();
Field[] fs = c.getDeclaredFields();
for (Field field : fs) {
//Get the class type of the type of member variable
Class fieldType = field.getType();
String typeName = fieldType.getName();
//Get the name of the member variable
String fieldName = field.getName();
System.out.println(typeName+" "+fieldName);
}
}
/**
 *  3.Print object constructor information
 * @param obj
 */
public static void printConMessage(Object obj){
Class c = obj.getClass();
/*
 * Constructors are also objects
 * java.lang. Constructor It encapsulates information about constructors
 * getConstructors Get all public constructors
 * getDeclaredConstructors Get all the constructors
 */
//Constructor[] cs = c.getConstructors();
Constructor[] cs = c.getDeclaredConstructors();
for (Constructor constructor : cs) {
System.out.print(constructor.getName()+"(");
//Get the parameter list of the constructor - > and get the class type of the parameter list.
Class[] paramTypes = constructor.getParameterTypes();
for (Class class1 : paramTypes) {
System.out.print(class1.getName()+",");
}
System.out.println(")");
}
}
}


* Reflection of Method
public class MethodDemo1 {
public static void main(String[] args) {
// To get print (int, int) method 1. To get a method is to get the information of the class. To get the information of the class, the first step is to get the class type of the class.
A a1 = new A();
Class c = a1.getClass();
// 2. Get method names and parameter lists to determine
try {
//Method m = c.getMethod("print", new Class[]{int.class,int.class});
Method m = c.getMethod("print", int.class,int.class); // parameter list has two ways, one way is to list an array directly
// Reflective operation of method
// a1.print(10, 20); the reflection operation of a method is to make method calls with m objects and a1.print calls have the same effect as a1.print calls.
// Method returns null if there is no return value, and return value returns specific return value.
//Object o = m.invoke(a1,new Object[]{10,20});
Object o = m.invoke(a1, 10,20);
System.out.println("==================");
// Get the method print(String,String)
Method m1 = c.getMethod("print",String.class,String.class);
// Reflective operation with method
//a1.print("hello", "WORLD");
o = m1.invoke(a1, "hello","WORLD");
System.out.println("===================");
// get method print()
// Method m2 = c.getMethod("print", new Class[]{});
Method m2 = c.getMethod("print");
// m2.invoke(a1, new Object[]{});
m2.invoke(a1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class A{
public void print(){
System.out.println("helloworld");
}
public void print(int a,int b){
System.out.println(a+b);
}
public void print(String a,String b){
System.out.println(a.toUpperCase()+","+b.toLowerCase());
}
}
* Understanding the essence of generics through Class and Method
ArrayList list = new ArrayList();
ArrayList<String> list1 = new ArrayList<String>();
list1.add("hello");
// list1.add(20); incorrect
Class c1 = list.getClass();
Class c2 = list1.getClass();
System.out.println(c1 == c2);//true
// Reflective operations are all compiled operations
/*
* The c1==c2 result returns true indicating that the generic type of the compiled collection is de-generic
* Generics of collections in Java are designed to prevent erroneous input. They are valid only at the compilation stage, and bypassing compilation is invalid.
* Verification: We can operate by reflection of methods, bypassing compilation
*/
try {
Method m = c2.getMethod("add", Object.class);
m.invoke(list1, 20); // / bypassing compilation operations bypasses generics
System.out.println(list1.size()); //2
System.out.println(list1); //[hello,20]
/*for (String string : list1) {
System.out.println(string);
}*/// You can't go through this now.
} catch (Exception e) {
e.printStackTrace();
}
* Get the attribute value of a standard javaBean object according to its attribute name
public static Object getValueByPropertyName(Object obj, String propertyName) {
// 1. The get method can be obtained according to the attribute name.
String getMethodName = "get"+ propertyName.substring(0, 1).toUpperCase()+ propertyName.substring(1);
// 2. Obtaining Method Objects
Class c = obj.getClass();
// get methods are public and have no parameters
Method m= c.getMethod(getMethodName);
// 3 Reflective operation method of passing method
Object value = m.invoke(obj);
return value;
}

Posted by jpschwartz on Tue, 09 Jul 2019 17:06:58 -0700