[road of transformation] day 47 frame foundation reflection (November 3, 2019)

Hello, Hello! I'm Alfie the programmer! Today, I would like to share with you the basic learning of framework reflection.

I. use of Class

1. In the object-oriented world, everything is an object.

Note: in the java language, static members and common data types are not objects.

Class is an object, and class is an instance object of java.lang.Class.

Foo foo1 = new foo(); / / instance object of foo

Any Class is an instance object of Class, which can be represented in three ways:

         Class c1 = Foo.class;

         Class c2 = foo1.getClass();

         Class c3 = null; c3 = Class.forName("com.imooc.reflect.Foo");

Everything is an object. A Class is also an example object of a Class. This object is called the Class type of this Class.

II. Java dynamic loading class

'class.forname' (full name of class)

    • It not only represents the class type of the class, but also represents the dynamically loaded class.

    • Please distinguish compilation and operation

    • The compile time load class is a static load class, and the runtime load class is a dynamic load class.     

Note:

    • The new creation object is a static loading class, which needs to load all possible classes at compile time.

    • This problem can be solved by dynamically loading classes.

class Officer{
public static void main(String[] args){
    if("word".equals(args[0])){
        Word word = new Word();
           word.start();
       }
       if("excel".equals(args[0])){
        Excel excel = new Excel();
           excel.start();
       }
   }
}
class OfficeBetter{
public static void main(String[] args){
    try{
        //Dynamically loading classes, loading at run time
           Class c = Class.forName(args[0]);
           //Create the class object through the class type
           OfficeAble oa = (OfficeAble)c.newInstance();
           oa.start();
       }catch(Exception e){
        e.printStackTrace();
       }
   }
}
class Word implements OfficeAble{
public void start(){
    system.out.printIn("word------");
   }
}
class Excel implements OfficeAble{
public void start(){
    system.out.printIn("excel------");
   }
}
//Summary: if there is only Word class and Office class is compiled directly, an error is reported in the background, indicating that Excel class cannot be found; if dynamic loading class is used, OfficeBetter class does not need to be recompiled every time.

III. Java access method information

public class ClassUtil{
public static void printClassMessage(Object obj){
    //Get class information
       Class c = obj.getClass();
       //Get the name of the class
       System.out.printIn("Class name:"+c.getName());
       /*
       * Method Class, method object table
       * A member Method is a Method object
       * getMethod()Method to get all public functions, including those inherited from the parent class
       * getDeclaredMethods(); Method to get the declaration of all classes
       */
       Method[] ms = c.getMethods();
       for(int i=0;i<ms.length;i++){
        //Gets the class type of the return value type of the method
           Class returnType = ms[i].getReturnType();
           System.out.printIn(returnType.getName()+" ");
           //Get the name of the method
           System.out.print(ms[i].getName()+"(");
           //Get parameter type - get the class type of parameter list
           Class[] paramTypes = ms[i].getParameterTypes();
           for(Class class1:paramTypes){
            System.out.print(class1.getName()+",");
           }
           System.out.print(")");
       }
   }
}
package com.wnf.reflect;

public class ClassDemo01 {
public static void main(String[] args) {
String name = "Hello World!";
ClassUtil.printClassMessage(name);
ClassDemo02 demo2 = new ClassDemo02();
ClassUtil.printClassMessage(demo2);
}
}

IV. get member variable constructor information in Java

Member variables are also objects

        java.lang.reflect.Filed

The file class encapsulates operations on member variables

The getfiles () method gets the information of all public member variables

Getdeclaredfields gets the information of the member variables declared by the class itself

Filed[] fs = c.getDeclaredFileds();
for(Filed filed:fs){
   //Gets the class type of the member variable's type
Class filedType = filed.getType();
   String typeName = fileType.getName();
   //Get the name of the member variable
   String filedName = filed.getName();
   System.out.printLn(typeName+""+filedName);
}
public static void printFieldMessage(Object obj) {
//Get information about member variables
Class c = obj.getClass();
Field[] fs = c.getFields();
for(Field field : fs){
Class fieldType = field.getType();
String typeName= fieldType.getSimpleName();
String fieldName = field.getName();
System.out.println(typeName+" "+fieldName);
}
}

//getConstructors() gets the public constructor
//getDeclaredConstructors() gets the constructor declared by the class itself
public static void printConMessage(Object obj){
//Get the constructor of this class
Class c = obj.getClass();
Constructor[] cr = c.getConstructors();
for (Constructor constructor : cr) {
System.out.print(constructor.getName()+"(");
Class[] paramTypes = constructor.getParameterTypes();
for (int j=0; j<paramTypes.length;j++) {
if(j==paramTypes.length-1){
System.out.print(paramTypes[j].getSimpleName());
}else{
System.out.print(paramTypes[j].getSimpleName()+",");
}
}
System.out.println(")");
}
}

V. basic operations reflected by Java methods

Reflection of △ method

1. How to get a method

Only the name of the method and the parameter list of the method can uniquely determine a method

2. Operation of method reflection

Method.invoke (object


, parameter list)

package com.imooc.reflect;

import java.lang.reflect.Method;

public class MethodDemo1 {
public static void main(String[] args) {
  //To obtain the print (int, int) method 1. To obtain a method is to obtain the class information. To obtain the class information, first obtain the class type of the class
A a1 = new A();
Class c = a1.getClass();
/*
* 2.Get the method name and parameter list to determine
* getMethod Get the public method
* getDelcaredMethod Method of self declaration
*/
   try {
//Method m =  c.getMethod("print", new Class[]{int.class,int.class});
    Method m = c.getMethod("print", int.class,int.class);
   
    //Reflection operation of method
    //a1.print(10, 20); the reflection operation of method is to use m object to make method call and the effect of a1.print call is exactly the same
       //Method if no return value returns null, 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 method print(String,String)
            Method m1 = c.getMethod("print",String.class,String.class);
            //Reflection operation with method
            //a1.print("hello", "WORLD");
            o = m1.invoke(a1, "hello","WORLD");
            System.out.println("===================");
          //  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());
}
}

6. Understand the nature of set generics through reflection

package com.imooc.reflect;

import java.lang.reflect.Method;
import java.util.ArrayList;

public class MethodDemo4 {
public static void main(String[] args) {
 ArrayList list = new ArrayList();
 
 ArrayList<String> list1 = new ArrayList<String>();
 list1.add("hello");
 //list1.add(20); wrong
 Class c1 = list.getClass();
 Class c2 = list1.getClass();
 System.out.println(c1 == c2);
 //The operations reflected are all operations after compilation
 
 /*
  * c1==c2 The result returns true, indicating that the generics of the compiled collection are de genericized
  * Java The generics of the collection in are to prevent erroneous input and are only valid in the compilation phase,
  * Bypass compilation is invalid
  * Validation: we can operate by reflection of methods, bypassing compilation
  */
 try {
  Method m = c2.getMethod("add", Object.class);
  m.invoke(list1, 20);//Bypassing the compile operation bypasses generics
  System.out.println(list1.size());
  System.out.println(list1);
  /*for (String string : list1) {
   System.out.println(string);
  }*///You can't traverse like this right now
 } catch (Exception e) {
   e.printStackTrace();
 }
}

}


Keywords: Java Excel

Added by vividona on Mon, 04 Nov 2019 01:22:35 +0200