Java reflection mechanism drip knowledge

What is the reflection

Get class file object mode   

  GetClass Object class () method of
  the data type of the static properties of class
  Class Static Method class
      public static Class forName (String className)

 

        // 方式1
        Person p = new Person();
        Class c = p.getClass();

        Person p2 = new Person();
        Class c2 = p2.getClass();

        System.out.println(p == p2);// false
        System.out.println(c == c2);// true

        // 方式2
        Class c3 = Person.class;
        // int.class;
        // String.class;
        System.out.println(c == c3);

        // 方式3
        // ClassNotFoundException
        Class c4 = Class.forName("renxixao.Person");
     System.out.println(c == c4); } }

Constructor reflected by obtaining and using

public class Person {
    private String name;
    int age;
    public String address;

    public Person() {
    }

    private Person(String name) {
        this.name = name;
    }

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Person(String name, int age, String address) {
        this.name = name;
        this.age = age;
        this.address = address;
    }

    public void show() {
        System.out.println("show");
    }

    public void method(String s) {
        System.out.println("method " + s);
    }

    public String getString(String s, int i) {
        return s + "---" + i;
    }

    private void function() {
        System.out.println("function");
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + ", address=" + address
                + "]";
    }

}

/ *
 * Constructor acquired by reflection and used.
 * /
Public class ReflectDemo {
    public static void main (String [] args) throws Exception {
       
        // Get bytecode file object
        Class c = Class.forName ( "renxixao.Person" );

        // public Constructor [] getConstructors () : all public constructors
        the Constructor [] = c.getConstructors Constructors ();
        for (CON the Constructor: Constructors) {
            System.out.println ( "public constructors:" + CON);
        }
       
        // public constructor [] getDeclaredConstructors () : all constructors
        the constructor [] = declaredConstructors c.getConstructors ();
        for (the constructor CON: declaredConstructors) {
            System.out.println ( "all constructors:" + CON);
        }
        / / public constructor <T> getConstructor ( <?> class ... parameterTypes) obtaining single constructor
        // class ... parameterTypes <?>: number of configuration parameters and data types of byte code class files acquired constructor Object
        constructor con = c.getConstructor (); // returns the object constructor
        T newInstance public // (Object ... initargs)
        // use constructor represented by this Constructor object to create a new instance of the class declaration of the constructor, and initializes the instance with the specified initialization parameters.
        = Con.newInstance obj Object ();
        System.out.println (obj);
        the Person P = (the Person) obj;
        p.show ();    
    }
}

operation result

Public constructor: public renxixao.Person (java.lang.String, int, java.lang.String)
public constructor: public renxixao.Person ()
All constructors: public renxixao.Person (java.lang.String, int, java.lang.String)
All constructor: public renxixao.Person ()
the Person [name = null, Age = 0, address = null]
Show

/ *
 * By reflecting this construction method to acquire and use:
 * public the Person (String name, int Age, String address)
 * /
public class ReflectDemo2 {
    public static void main (String [] args) throws Exception {
        // BYTE code file object
        Class C = the Class.forName ( "renxixao.Person");
        // constructor parameter acquisition target tape
        // public the constructor <T> getConstructor (Class ... The parameterTypes <?>)
        the constructor c.getConstructor CON = ( String.class, int.class,
                String.class);
        // create an object by reference, with the object constructor
        // public T newInstance (Object ... initargs)
        Object obj = con.newInstance ( "Bob", 27, "Beijing ");
        System.out.println (obj);
    }
}

 

Person [name = Hsiao Ming, age = 27, address = Beijing]

 

Private constructor reflected by obtaining and using

 

/ *
 * Requirements: obtaining by the reflection method, using a private constructor
 * Private the Person (String name) {}
 * /
public class ReflectDemo3 {
    public static void main (String [] args) throws Exception {
        // Get bytecode file object
        Class c = Class.forName ( "renxixiao.Person") ;

        // Get the private constructor method of the object
        // NoSuchMethodException: This method each abnormal
        // The reason is the beginning of the method we use only get public, here in this way on it.
        Constructor con = c.getDeclaredConstructor (String.class);

        // create an object with the private constructor
        // IllegalAccessException: illegal access exception.
        // Violence access
        con.setAccessible (true); // value of true indicates that the object is reflected in the use of the Java language access checks should be canceled.
        Object obj = con.newInstance ( "Bob");
        System.out.println (obj);
    }
}

Must be set to obtain private construction con.setAccessible (true) otherwise appear IllegalAccessException: illegal access exception.

By acquiring member variables reflecting acquisition and use

/ *
 * Occurs through the acquisition and use of member variables
 * /
public class ReflectDemo {
    public static void main (String [] args) throws Exception {
        // Get bytecode file object
        Class c = Class.forName ( "renxixiao.Person" ) ;

        // Get all the member variables
        Field [] fields = c.getFields () ; // get all of the member variables
        Field [] declaredFields = c.getDeclaredFields () ; // get the private member variables
        for (Field field: fields) {
        System.out.println ( "common member variables" Field +);
        }
        for (Field, Field: declaredFields) {
            System.out.println ( "private member variables" Field +);
        }

        // constructor creates an object by reference without
        the Constructor c.getConstructor = CON ();
        Object obj = con.newInstance ();

        // Get a single member variables
        // Get the address and its assignment
        Field addressField = c.getField ( "address" );
        field // public void set (Object obj, Object value) will this Field object on the specified object variable represents to the new value specified.
        addressField.set (obj, "Beijing"); // object obj to addressField field setting value is "Beijing"
        System.out.println (obj);

        // Get the name and its assignment
        // a NoSuchFieldException
        Field, nameField = c.getDeclaredField ( "name");
        // IllegalAccessException
        nameField.setAccessible (to true);
        nameField.set (obj, "Xiao Ming");
        System.out.println ( obj);

        // Get age and their assignment
        Field, ageField = c.getDeclaredField ( "age");
        ageField.setAccessible (to true);
        ageField.set (obj, 27);
        System.out.println (obj);
    }
}

All member variables public java.lang.String renxixiao.Person.address
private member variables private java.lang.String renxixiao.Person.name
private member variables int renxixiao.Person.age
private member variables public java.lang.String renxixiao.Person.address
the Person [name = null, age = 0, address = null]
the Person [name = null, age = 0, address = Beijing]
the Person [name = Xiaoming, age = 0, address = Beijing]
the Person [name = Xiaoming, age = 27, address = Beijing]

Obtaining by acquiring reflection method and using

/ *
 * Occurred by obtaining and using methods
 * /
public class ReflectDemo {
    public static void main (String [] args) throws Exception {
        // Get bytecode file object
        Class c = Class.forName ( "renxixiao.Person" );

        // Get all methods
        Method [] methods = c.getMethods () ; // Public method comprising obtaining their father's
        Method [] methodss = c.getDeclaredMethods () ; // get all of their methods
        for (Method method : methods) {
        System.out.println ( "public methods" + method);
        }
        for (method, method: methodss) {
            System.out.println ( "all the way" + method);
            }
        the Constructor c.getConstructor CON = ( );
        Object obj = con.newInstance ();

       
        // Get and use a single method
        // public void Show ()
        // public Method, getMethod (String name, Class <?> ... parameterTypes)
        // method name of the first parameter representation, the second parameter is class type parameter method
        method, M1 = c.getMethod ( "Show");
        // Invoke public Object (Object obj, args ... Object)
        // Object return value is received, the first parameter indicates who is the object, the second parameter indicates the actual parameters of the method call
        m1.invoke (obj); // call method m1 object obj
        System.out.println ( "----------");
        // public void method (String S)
        Method, M2 = c.getMethod ( "Method", String.class);
        m2.invoke (obj, "Hello");
        System.out.println ( "----------") ;

        // public String getString(String s, int i)
        Method m3 = c.getMethod("getString", String.class, int.class);
        Object objString = m3.invoke(obj, "hello", 100);
        System.out.println(objString);
        // String s = (String)m3.invoke(obj, "hello",100);
        // System.out.println(s);
        System.out.println("----------");

        // private void function()
        Method m4 = c.getDeclaredMethod("function");
        m4.setAccessible(true);
        m4.invoke(obj);
    }
}

Public method public java.lang.String renxixiao.Person.toString ()
Public method public java.lang.String renxixiao.Person.getString (java.lang.String, int)
Public method public void renxixiao.Person.method (java.lang .string)
public method public void renxixiao.Person.show ()
public method public final void java.lang.Object.wait () throws java.lang.InterruptedException
public method public final void java.lang.Object.wait (long, int ) throws java.lang.InterruptedException
public method public final native void java.lang.Object.wait (long) throws java.lang.InterruptedException
public method public boolean java.lang.Object.equals (java.lang.Object)
public method public native int java.lang.Object.hashCode ()
public method public final native java.lang.Class java.lang.Object.getClass ()
Public Methods public final native void java.lang.Object.notify ()
Public method public final native void java.lang.Object.notifyAll ()
all methods public java.lang.String renxixiao.Person.toString ()
all the way to private void renxixiao.Person.function ()
All methods public java.lang.String renxixiao.Person.getString (java.lang.String, int)
all methods public void renxixiao.Person.method (java.lang.String)
all methods void renxixiao.Person.show public ()
Show
----------
method, the Hello
----------
the Hello --- 100
----------
function

Guess you like

Origin www.linuxidc.com/Linux/2019-09/160495.htm