Home IT Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Java reflection summary     - Udev: Device Manager for Linux Fundamentals (Linux)

- rpm package specify the installation path (Linux)

- SSH without password (Linux)

- To install CentOS 6.5 on your hard drive under Windows 7 (Linux)

- Oracle how to assess the true concurrent session (Database)

- Calculate CPU utilization (Linux)

- CentOS modify yum update source (Linux)

- RHEL5 / 6 Installation Notes (Linux)

- SQL Server memory Misunderstanding (Database)

- Kickstart automated installation and deployment RHEL 7.0 (Linux)

- Virtualization and IT cooperation (Linux)

- Oracle 10g in the unique and index problems (Database)

- MongoDB 3.2 Cluster Setup (Database)

- Let OS X support NTFS write file (Linux)

- Check the Linux server performance with ten or so commands in a minute (Server)

- Linux-- sub-volume compression and decompression (Linux)

- Detailed driver compiled into the Linux kernel (Programming)

- Use value type build better applications Swift (Programming)

- Qt signals and slots mechanism (Programming)

- MongoDB replication instance (Database)

 
         
  Java reflection summary
     
  Add Date : 2016-10-14      
         
       
         
  Ability to analyze the program class called reflection. For a given Java class name, you can get the kind of information through reflection, map the ingredients like the corresponding Java class.

A, Class category

    During program execution, the system always identifies the type of maintenance is known as a runtime for all objects Java runtime. This information trace the class for each object belongs. The virtual machine runtime type information to select the appropriate method of execution. You can access this information through special Java classes. Save this information class named Class.

Create Class class object in three ways:

1. getClass method

    Object The getClass method returns an instance of Class type.

 
class Person {
   // ...
}

Person p = new Person ();
Class c = p.getClass ();
 
2. forName method

    You can get the class name corresponding Class object via the static method forName.

 
String className = "java.util.Date";
Class c = Class.forName (className);
 
    If you need to during operation need to change the class name, you can use this method. Of course, the string className must be a class name or interface (including the package name), there would be an exception.

3. T.class

Class c1 = Date.class;
Class c2 = int.class;
Class c3 = Double [] class.;
    T represents an arbitrary Java type. Get matching class object through T.class.

Note: a real Class object represents a type, but not necessarily of this type is a class.
Virtual machine for each type of management a Class object. So you can use the == operator to compare two classes implement objects

if (p.getClass () == Person.class) {...}
newInstance method

    You can create an instance of a class by newInstance method.

Person person = p.getClass () newInstance ().;
    It creates an instance of the same class with the p type. newInstance call the default constructor to initialize the object is created. If the class does not have a default constructor will throw an exception.

Second, the use of analytical reflection class structure

Get the package name + class name (including the name of the parent class)

package com.xiaoxiaoyihan.reflection;

class Person {
    // ...
}

class Student extends Person {

}

public class ReflectionDemo1 {
    public static void main (String [] args) {
        Student s = new Student ();
        Class cl = s.getClass ();
        Class superCl = cl.getSuperclass ();
        System.out.println ( "Get Class Name:" + cl.getName ());
        System.out.println ( "Get the parent class name:" + superCl.getName ());
    }
}
[Run] Results:
Get the class name: com.xiaoxiaoyihan.reflection.Student
Get the name of the parent class: com.xiaoxiaoyihan.reflection.Person

Note: If a class in a package, the package name as part of the class name.
Expansion point:

First look at an example:

class Person {
    private String name = "Xiao Xiao Yi cold";
    // Omitted setter and getter
}
class Animal {
    private String name = "paqi";
    // Omitted setter and getter
}

Person p;
Animal a;
Class cPerson = p.getClass ();
Class cAnimal = a.getClass ();
// CPerson.getName () Gets the class name, p.getName () is the name attribute value of the Person instance
System.out.println (cPerson.getName () + "<--->" + p.getName ());
System.out.println (cAnimal.getName () + "<--->" + p.getName ());
[Run] Results:
com.xxyh.reflec.Person <---> Xiaoxiao Yi Han
com.xxyh.reflec.Animal <---> paqi

It showed a Person object p represents a specific person's attributes, one Animal object is a representation of a particular animal property, a Class object represents a particular class (Person or Animal) properties. From this point of view, it is an instance of Class objects.

Analytical constructor (Constructor)

Class class getConstructors method returns an array of public constructors. Class class getDeclaredConstructors returns an array class constructor declared.

package com.xiaoxiaoyihan.reflection;

import java.lang.reflect.Constructor;
class Person {
    private String name;
    private int age;

    private Person () {}

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

    public Person (String name, int age) {
        this.name = name;
        this.age = age;
    }
}
public class ReflectionDemo1 {
    public static void main (String [] args) throws ClassNotFoundException {
        Class cl = Class.forName ( "com.xiaoxiaoyihan.reflection.Person"); // directly thrown to simplify the code

        Constructor [] constructors = cl.getDeclaredConstructors ();
        // Constructor [] constructors = cl.getConstructors ();
        for (Constructor c: constructors) {
            System.out.println (c);
        }
    }
}
[Run] Results:

private com.xiaoxiaoyihan.reflection.Person ()
protected com.xiaoxiaoyihan.reflection.Person (java.lang.String)
public com.xiaoxiaoyihan.reflection.Person (java.lang.String, int)

// Public com.xiaoxiaoyihan.reflection.Person (java.lang.String, int) // This section is run getConstructors method output

An analysis of the results, you will find by System.out.println (c); constructor direct printing is composed of several parts, including the parameter modifiers (public / protected / private), class name and constructor, so, these are part of how to get it?

It contains static methods getModifiers method Modifier class, which returns an integer i, expressed public, static with different values, final such modifiers. Modifier Static method toString (i) returns the corresponding modifier. Constructor class contains the static methods getParameterTypes, it returns an array of Class objects described parameter types.

package com.xiaoxiaoyihan.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;

class Person {
    private String name;
    private int age;

    private Person () {}

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

    public Person (String name, int age) {
        this.name = name;
        this.age = age;
    }
}
public class ReflectionDemo1 {
    public static void main (String [] args) throws ClassNotFoundException {
        Class cl = Person.class;

        Constructor [] constructors = cl.getDeclaredConstructors ();
        for (Constructor c: constructors) {
            // Get the package name and class name
            String name = c.getName ();

            // Get modifiers
            String modifiers = Modifier.toString (c.getModifiers ());
            if (modifiers.length ()> 0) {// if modifier
                System.out.print (modifiers + "");
            }

            System.out.print (name + "(");

            // Get parameter type constructor
            Class [] paramTypes = c.getParameterTypes ();

            for (int i = 0; i                 if (i> 0) {// If more than one parameter, use "," split the parameter type
                    System.out.print ( ",");
                }
                System.out.print (paramTypes [i] .getName ());
            }
            System.out.println ( ");");
        }

    }
}
[Run] Results:

private com.xiaoxiaoyihan.reflection.Person ();
protected com.xiaoxiaoyihan.reflection.Person (java.lang.String);
public com.xiaoxiaoyihan.reflection.Person (java.lang.String, int);

Analytical method (Method)

Class class getMethods method returns an array that includes all of the methods of the class from the method interface, the public (public) method of the parent class public methods of the parent class of the parent class ...... Object has been extended to the public method. getDeclaredMethods this method returns the class declaration method, the method from the interface implementation.

package com.xiaoxiaoyihan.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;


class Person / * extends Object * / {
    private void privateMethodPerson () {
        // ...
    }

    protected void protectedMethodPerson () {
        // ...
    }

    public void publicMethodPerson () {
        // ...
    }
}

interface Smoke {
    void smoking ();
}

class Student extends Person implements Smoke {
    @Override
    public void smoking () {
        // ...
    }

    private void privateMethodStudent () {
        // ...
    }

    protected void protectedMethodStudent () {
        // ...
    }

    public void publicMethodStudent () {
        // ...
    }
}


public class ReflectionDemo1 {
    public static void main (String [] args) {
        Student s = new Student ();
        Class cl = s.getClass ();
        Method [] methods = cl.getDeclaredMethods ();
// Method [] methods = cl.getMethods ();

        for (Method m: methods) {
            System.out.println (m);
        }
    }
}
[Run] Results:

public void com.xiaoxiaoyihan.reflection.Student.smoking ()
protected void com.xiaoxiaoyihan.reflection.Student.protectedMethodStudent ()
private void com.xiaoxiaoyihan.reflection.Student.privateMethodStudent ()
public void com.xiaoxiaoyihan.reflection.Student.publicMethodStudent ()

The above examples give an inheritance structure intentionally, in order to view the getMethods result, this will not give the results. Note Person default inherit Object class. Incidentally, the author (non-self-Coban rookie) had asked Object in which the interview method, estimated that he would like to know what methods are commonly used, and I did not answer the whole ~ 2333, readers do not know you at a glance the results? ? .

Similarly, we see the above System.out.println (m); print out the method consists of modifier, the return value, class name, method name and parameters. So if these parts get it? Similar to Construction Class, Method class also provides static methods getParamTypes, the method returns an array of Class objects described parameter types. In addition, Method getReturnType also provides methods for getting the return type of Class objects.

package com.xiaoxiaoyihan.reflection;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

class Person {

    private String name = "Xiao Xiao Yi cold";

    public String getName () {
        return name;
    }

    public void setName (String name) {
        this.name = name;
    }

    public static void speak () {
        // ...
    }

    public final void eat () {
        // ...
    }
}


public class ReflectionDemo1 {
    public static void main (String [] args) {

        Class cl = Person.class;

        Method [] methods = cl.getDeclaredMethods ();
        for (Method m: methods) {
            // Return type of Object Class
            Class retType = m.getReturnType ();
            //
            String retTypeName = retType.getName ();

            // Get the name of the method
            String name = m.getName ();

            String modifiers = Modifier.toString (m.getModifiers ());
            if (modifiers.length ()> 0) // if modifier
                System.out.print (modifiers + "");

            // Return value name
            System.out.print (retType.getName () + "");

            System.out.print (name + "(");

            Class [] paramTypes = m.getParameterTypes ();
            for (int i = 0; i                 if (i> 0) {// If more than one parameter, use "," split
                    System.out.print (paramTypes [i] .getName ());
                }
            }
            System.out.println ( ");");
        }

    }
}
[Run] Results:
public java.lang.String getName ();
public void setName ();
public static void speak ();
public final void eat ();

To resolve a domain (Field)

Class class getDeclaredFields method returns an array of fields declared in the class, getFields method returns the class of the public domain, Field array of objects in the interface region thereof.

package com.xiaoxiaoyihan.reflection;

import java.lang.reflect.Field;
import java.util.Date;

class Person {
    private String name;
    protected int age;
    public Date birthday;
}

class Student extends Person implements Smoke {
    private float score;
}

interface Smoke {
    String brand = "Greater China";
}

public class ReflectionDemo1 {
    public static void main (String [] args) {
        Class cl = Student.class;

        Field [] fields = cl.getFields ();
        for (Field f: fields) {
            System.out.println (f);
        }
    }
}
[Run] Results:
public static final java.lang.String com.xiaoxiaoyihan.reflection.Smoke.brand
public java.util.Date com.xiaoxiaoyihan.reflection.Person.birthday

    The results show that the field consists of modifier, type, class name, field name constituted. It should be introduced into the Field class getType method that returns the type of field declaration of Class objects. Also make the following analysis:

package com.xiaoxiaoyihan.reflection;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Date;

class Person {
    private String name;
    protected int age;
    public Date birthday;
}

public class ReflectionDemo1 {
    public static void main (String [] args) {
        Class cl = Person.class;

        Field [] fields = cl.getDeclaredFields ();
        for (Field f: fields) {
            // Class object attribute types
            Class type = f.getType ();

            // Attribute type name
            String name = type.getName ();
            System.out.print ( "");

            // Modifiers
            String modifiers = Modifier.toString (f.getModifiers ());

            if (modifiers.length ()> 0) {// if modifier
                System.out.print (modifiers + "");
            }

            System.out.println (type.getName () + "" + name + ";");
        }
    }
}
[Run] Results:

private java.lang.String java.lang.String;
protected int int;
public java.util.Date java.util.Date;

Operation object properties (domain) value
    As already know how to find any object in the domain name and data type. When writing a program, if you want to see the domain name and type is a very simple thing, and reflection can be viewed in the object domain compilation Shihai unclear.

Use get method to get the domain (property) values

    View object is to get the key domain method Field class. If f is an object of type Field, obj is a class containing f domain objects, f.get (obj) returns an object of type Object, its value is the current value of obj field. Example:

package com.xiaoxiaoyihan.reflection;

import java.lang.reflect.Field;

class Person {
    private String name;

    public Person (String name) {
        this.name = name;
    }
}
public class ReflectionDemo2 {
    public static void main (String [] args) throws NoSuchFieldException, IllegalAccessException {
        Person p = new Person ( "Xiao Xiao Han Yi");

        Class clz = p.getClass ();
        Field f = clz.getDeclaredField ( "name");
        //f.setAccessible(true);
        Object name = f.get (p);

        System.out.println (name);
    }
}
[Run] Results:

Exception in thread "main" java.lang.IllegalAccessException: Class com.xiaoxiaoyihan.reflection.ReflectionDemo2 can not access a member of class com.xiaoxiaoyihan.reflection.Person with modifiers "private"
at sun.reflect.Reflection.ensureMemberAccess (Reflection.java:109)
......

Note: Because the default behavior is limited to the Java reflection mechanism of access control. If a Java program is not limited to the security manager's control, you can override access control. Field, Method, or Constructor object provides setAccessible method for covering access control.
get methods also need to address another problem, get the return value is of type Object, the above name of type String, the String type value assigned to the object Object no problem, but if there is double what types of domains? Value types are not objects Java. The method can getDouble Field class, or you can call the get method and then cast. Reflection mechanism automatically package the value in this field to the appropriate object wrapper for double type, it will be packaged into a Double.

package com.xiaoxiaoyihan.reflection;

import java.lang.reflect.Field;

class Person {
    private double salary;

    public Person (double salary) {
        this.salary = salary;
    }
}
public class ReflectionDemo2 {
    public static void main (String [] args) throws NoSuchFieldException, IllegalAccessException {
        Person p = new Person (100);

        Class clz = p.getClass ();

        Field f = clz.getDeclaredField ( "salary");
        f.setAccessible (true);
// Double salary = (double) f.get (p);
        double salary = f.getDouble (p);
        System.out.println ( "Salary:" + salary);
    }
}
[Run] Results:
Salary: 100.0

Use set methods set the domain (property) values

Of course, you can use the set method, the object obj f field to set a new value. Signature set method is:

void set (obj, value) // obj: object manipulation; value: new value
Example:

package com.xiaoxiaoyihan.reflection;

import java.lang.reflect.Field;

class Person {
    private String name;
    private double salary;

    public Person (String name, double salary) {
        this.name = name;
        this.salary = salary;
    }

    public double getSalary () {
        return salary;
    }

    public String getName () {
        return name;
    }
}
public class ReflectionDemo2 {
    public static void main (String [] args) throws NoSuchFieldException, IllegalAccessException {
        Person p = new Person ( "Joe Smith", 100);

        System.out.println (p.getName () + "-----" + p.getSalary ());

        Class clz = Person.class;

        Field f = clz.getDeclaredField ( "name");
        f.setAccessible (true);
        f.set (p, "Xiao Xiao Han Yi");

        f = clz.getDeclaredField ( "salary");
        f.setAccessible (true);
        f.set (p, 200);

        System.out.println (p.getName () + "-----" + p.getSalary ());

    }
}

Call any method

invoke method

Methods Field class and get a domain similar view objects, invoke Method class provides a method that allows the caller to packing methods in current Method object. Signed invoke method are:

Object invoke (Object obj, Object ... args)
The first parameter is the implicit argument, the rest of the object provides the display parameters.

For example, m1 representatives of Person getName method, then get the name of the form by the invoke method:

String n = m1.invoke (p);
If the return is the basic type, invoke method returns the type of packaging. For example, m2 represents getSalary method, the object is returned is actually a Double, you must respond to the full conversion.

double s = m2.invoke (p);
According to the Java reflection Summary (1): parsing class structure introduced by the static method of class Class getDeclaredMethods Method Gets an array of objects, and then traverse the array returned to find the specified method. Similar getField method, getField string representation domain method returns a Field object. However, due to the presence of overloaded methods, it is possible to obtain a plurality of the same name method. Therefore, you must provide the parameter type of the method. getMethod method signature:

Method getMethod (String name, Class ... paramTypes)
Example:

package com.xiaoxiaoyihan.reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

class Person {
    private String name;
    private double salary;

    public String getName () {
        return name;
    }

    public double getSalary () {
        return salary;
    }

    public void raiseSalary (double raise) {
        salary + = raise;
    }

    public Person (String name, double salary) {
        this.name = name;
        this.salary = salary;
    }

}

public class ReflectionDemo2 {
    public static void main (String [] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Person p = new Person ( "Xiao Xiao Han Yi", 100);

        // Get the getName method of the object
        Method m1 = p.getClass () getMethod ( "getName").;
        // Call the getName method
        String name = (String) m1.invoke (p);
        System.out.println ( "My name is:" + name);

        // Get raiseSalary method of the object, double type parameters need to be passed
        . Method m2 = p.getClass () getMethod ( "raiseSalary", double.class);
        // Call raiseSalary, passing the parameter values
        m2.invoke (p, 200);
        System.out.println ( "After salary: salary =" + p.getSalary ());
    }
}
[Run] Results:
My name is: Xiao Xiao Yi Han
After a raise: salary = 300.0

For static methods, invoke the first argument can be ignored, either set it to null.

package com.xiaoxiaoyihan.reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

class Person {
    public static void speak (String name) {
        System.out.println ( "Wood!" + Name + ", you'd say ah!");
    }

}

public class ReflectionDemo2 {
    public static void main (String [] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method m = Person.class.getMethod ( "speak", String.class);
        m.invoke (null, "Yi Xiao Xiao Han");

    }
}
[Run] Results:
wood! Xiao Xiao Yi cold, you just say ah!

Note: invoke parameters and return value must be of type Object. This means that the need for multiple types of conversions. Doing so will be checking code compiler missed opportunities. In addition, the method for obtaining the code pointer by reflecting lower efficiency than the direct method call.
     
         
       
         
  More:      
 
- systemd-nspawn Quick Guide (Linux)
- how to quickly find a file on Linux system (Linux)
- Root of AVL Tree- achieve balanced search trees AVL tree (Programming)
- Linux shell script to adjust the Task Scheduler (Linux)
- Oracle RMAN repair logical bad blocks (Database)
- Java implementation heap sort (large root heap) (Programming)
- Linux uses shared memory communication process synchronization Withdrawal (Programming)
- Physical structure and process disk IO (Linux)
- Port is not being used, how will bind failure? (Server)
- Preliminary understanding of SELinux security management (Linux)
- Linux Kernel 4.2 Installation Instructions (Linux)
- How to manage KVM virtual environments with command-line tools in Linux (Server)
- Preview function to confirm the stop resource Oracle 12c new feature crsctl (Database)
- Hadoop - Task Scheduling System Comparison (Server)
- Linux System Tutorial: How to Check MariaDB server versions (Database)
- Linux system security settings after installation (Linux)
- Linux server operating system security configuration (Linux)
- How to use SHA256 checksum files download (Linux)
- After VMware CentOS full VM clone the network card is unavailable Solutions (Linux)
- Install Redis 2.6 5.5 32 position CentOS error resolved (Linux)
     
           
     
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.