java Reflection Summary example in detail

  • 2020-06-23 00:23:11
  • OfStack

1. Class class

Any class is an instance object of Class, which is represented in three ways

// The first way -- > It's actually telling us that every class has an implicit static member variable class

Class c1 = User.class;

The representation in // 2 already knows the object of the class through the getClass method

User user = new User();

Class c2 = user.getClass();

c1,c2 represents the class type of User class (class type)

* Everything is an object,

The * class is also an object, an instance object of the Class class

* This object is called the class type of the class

// Regardless of 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 expression

Class c3 = Class.forName("com.wx.model.User");

System.out.println(c2==c3);===true

As you know above, each class has one and only one class type of its own class

// It is entirely possible to create an object instance of a class by its class type > Create an instance object of User with c1 or c2 or c3

User user = (User)c1.newInstance();// A parameterless construction method is required

Class.forName (full name of the Class)

Represents not only the class type of the class, but also the dynamically loaded class

Distinguish between compiled and run compile-time loaded classes being statically loaded and run-time loaded classes being dynamically loaded

* When compiling, if several objects are declared in one class, several classes will be created, no matter whether it is used or not, otherwise an error will be reported. That is, new statically loads classes when creating objects, so all possible classes should be loaded during compilation. So there are ways 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]);// Dynamically loads classes that are loaded at run time  
People p = (People)c.newInstance();// The class object is created by the class type  
p.start(); 
} 
} 

* Basic data types


public class ClassDemo2 { 
 public static void main(String[] args) { 
  Class c1 = int.class;//int  The class type  
  Class c2 = String.class;//String Class type of a class  String Class bytecode (self invention ) 
  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 the class that does not contain the package name  
  System.out.println(c5.getName()); 
 } 
} 

Results:

int

java.lang.String

String

void

* Class reflection


public class ClassUtil { 
/** 
 *  Print class information, including class member functions, member variables ( Gets only member functions ) 
 * 1. Access method  
 * @param obj  Information about the class to which the object belongs  
 */ 
public static void printClassMethodMessage(Object obj){ /* String s = "hello"; s is String Type of object  */ 
// To get information about the class   The first step is to get the class type of the class  
Class c = obj.getClass();// The first 2 Which subclass of object is passed by the method  c Is the class type of the subclass  
// Gets 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  
 * 1 The member method is 1 a Method object  
 * getMethods() Method gets all of them public Functions, including those inherited from the parent class  
 * getDeclaredMethods() Gets all methods declared by the class itself, regardless of access rights  
 */ 
Method[] ms = c.getMethods();//c.getDeclaredMethods() 
for(int i = 0; i < ms.length;i++){ 
// Gets the class type of the method's return value type  
Class returnType = ms[i].getReturnType(); 
System.out.print(returnType.getName()+" ");  // Return type name: bollean 
// Gets the name of the method  
System.out.print(ms[i].getName()+"(");   //equals( 
// Get parameter type ---> The result is an array of class types of the type of the argument list  
Class[] paramTypes = ms[i].getParameterTypes(); 
for (Class class1 : paramTypes) { 
System.out.print(class1.getName()+",");  //java.lang.Object, 
} 
System.out.println(")");      //) 
} 
} 
 /** 
  * 2. Gets information about a member variable  
  * @param obj 
  */ 
public static void printFieldMessage(Object obj) { 
Class c = obj.getClass(); 
/* 
 *  Member variables are also objects  
 * java.lang.reflect.Field 
 * Field Class encapsulates operations on member variables  
 * getFields() Method gets all of them public Information about the member variables of  
 * getDeclaredFields Gets information about the member variables declared by the class itself  
 */ 
//Field[] fs = c.getFields(); 
Field[] fs = c.getDeclaredFields(); 
for (Field field : fs) { 
// Gets the class type of the type of the member variable  
Class fieldType = field.getType(); 
String typeName = fieldType.getName(); 
// Gets the name of the member variable  
String fieldName = field.getName(); 
System.out.println(typeName+" "+fieldName); 
} 
} 
/** 
 * 3. Prints information about the constructor of the object  
 * @param obj 
 */ 
public static void printConMessage(Object obj){ 
Class c = obj.getClass(); 
/* 
 *  Constructors are also objects  
 * java.lang. Constructor Encapsulates the information for the constructor  
 * getConstructors Get all of the public Constructor of  
 * getDeclaredConstructors Get all the constructors  
 */ 
//Constructor[] cs = c.getConstructors(); 
Constructor[] cs = c.getDeclaredConstructors(); 
for (Constructor constructor : cs) { 
System.out.print(constructor.getName()+"("); 
// Gets the constructor's argument list ---> The result is the class type of the argument list  
Class[] paramTypes = constructor.getParameterTypes(); 
for (Class class1 : paramTypes) { 
System.out.print(class1.getName()+","); 
} 
System.out.println(")"); 
} 
} 
} 

* Method reflection


public class MethodDemo1 {
public static void main(String[] args) {
// To obtain a print(int ,int ) methods  1. To obtain a 1 The method is to get the information of the class. The first thing to get the information of the class is the class type of the class 
A 
a1 = new A();
Class c = a1.getClass();
// 2. Access method   Name and parameter list to determine 
try {
//Method m = c.getMethod("print", new Class[]{int.class,int.class});
Method m
= c.getMethod("print", int.class,int.class);// There are two ways to do this 1 An array of 1 The species are listed directly 
// Method  
//a1.print(10, 20); The method's reflection operation is used m Object to make method calls   and a1.print The effect is exactly the same 
// Method returns if no value is returned null, There are return values that return specific return values 
//Object o = m.invoke(a1,new Object[]{10,20});
Object o = m.invoke(a1, 10,20);
System.out.println("==================");
// Access method print(String,String)
Method m1 = c.getMethod("print",String.class,String.class);
// Method for reflection operation 
//a1.print("hello", "WORLD");
o = m1.invoke(a1, "hello","WORLD");
System.out.println("===================");

// Access 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());
}
}
* through Class . Method To understand the nature of generics 

ArrayList list = new ArrayList();
ArrayList<String> list1 = new ArrayList<String>();
list1.add("hello");
//list1.add(20); The wrong 
Class c1 = list.getClass();
Class c2 = list1.getClass();
System.out.println(c1 == c2);//true
// Reflection operations are compiled 
/*
* c1==c2 Results back true Specifies that the generics of a compiled collection are de-generified 
* Java Is a collection of generic, is to prevent the wrong input, only in the compilation phase, bypassing the compilation is invalid 
*  Validation: We can bypass compilation by means of method reflection 
*/
try {
Method m = c2.getMethod("add", Object.class);
m.invoke(list1, 20);// Bypassing compilation bypasses generics 
System.out.println(list1.size());
//2
System.out.println(list1);
//[hello,20]
/*for (String string : list1) {
System.out.println(string);
}*/// Now you can't iterate like this 
} catch (Exception e) {
e.printStackTrace();
}
*  According to the standard javaBean The property name of the object gets its property value 
public static Object getValueByPropertyName(Object obj, String propertyName) {
// 1. You can retrieve it by its name get methods 
String getMethodName = "get"+ propertyName.substring(0, 1).toUpperCase()+ propertyName.substring(1);
//2. Get method object 

Class c = obj.getClass();

//get Methods are public And has no parameters 

Method m= c.getMethod(getMethodName);

//3  A reflection operation by a method 

Object value = m.invoke(obj);

return value;
}

I hope this article has been helpful in java programming


Related articles: