Home IT Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Analysis of Java reflection mechanism     - How to add two-factor authentication for Linux systems SSH (Linux)

- To install Python-Pip and Fabric under CentOS / Ubuntu (Linux)

- The method of CentOS-7.0. The installation and configuration of Tomcat-7 (Server)

- PostgreSQL transaction model introduction (Database)

- Using Linux command line and execute PHP code (Programming)

- Build ASP.NET 5 development environment in Ubuntu (Server)

- Struts2 configure a static resource files without Struts processing (regular match) (Programming)

- Linux install and configure Heartbeat (Server)

- The Oracle VM VirtualBox use U disk under ubuntu (Linux)

- Windows7 / 8 / 8.1 hard drive to install Ubuntu 14.04 dual system (Linux)

- java.net.NoRouteToHostException of Hadoop problem: no route to host (Server)

- Hardware Firewall Basics (Linux)

- CentOS7 boot systemd introduction and use of management (Linux)

- True and false in Perl (Programming)

- Open MySQL slow query log (Database)

- How to Install Apache on Linux servers (Server)

- Deploy OpenStack Juno on Ubuntu 14.04 (Linux)

- Extended VMware Ubuntu root partition size (Linux)

- How to prevent page five invisible killer (Linux)

- SSH does not require a password to log on to a Linux server (Server)

 
         
  Analysis of Java reflection mechanism
     
  Add Date : 2017-01-08      
         
       
         
  Concept
Java reflection mechanism is in the operating state, for any class, we are able to know all the properties and methods of this class; For any object, you can call any of its methods and properties; obtain information about this dynamic and the dynamic call the method is called a functional object reflection java language.

Class class libraries together with java.lang.reflect concept was reflected support the library contains the Field, Method and Constructor classes (each class implements the Member interface). These types of objects are created by the JVM at run time, to indicate the corresponding member in the unknown class. So developers can use the Constructor to create new objects, methods to read and modify the object associated with the Field field with the get () and set (), using invoke method calls associated Method object methods (). In addition, you can also call getFields (), getMethods (), getConstructors () and so very convenient method to return the array representing the fields, methods and constructors of objects. This type of information is completely anonymous objects can be recognized in the running down, and at compile time does not need to know anything.

Class

Class is part of the program, each class has a Class object. In other words, whenever the write and compile a new class, it will generate a Class object (more properly speaking, is stored in .class file of the same name), which contains information pertaining to the class. In order to generate this kind of object, the virtual machine running this object (JVM) will be used is called "class loader (ClassLoader)" subsystem. Some basic information about the following test class.

public class ClassInfo {
 
    / **
    * @description Format output differently class name
    * @param Clazz
    * /
    public static void printName (Class clazz) {
        System.out.println ( "getName:" + clazz.getName ());
        System.out.println ( "getCanonicalName:" + clazz.getCanonicalName ());
        System.out.println ( "getSimpleName:" + clazz.getSimpleName ());
    }
    
    / **
    * Parent @description output classes and interfaces
    * @param Clazz
    * /
    public static void printClassIntf (Class clazz) {
         Class superClass = clazz.getSuperclass ();
         Class [] interfaces = clazz.getInterfaces ();
        if (superClass! = null) {
            System.out.print (clazz.getSimpleName () + "extends" + superClass.getSimpleName ());
        }
        if (interfaces.length> 0) {
            System.out.print ( "implements");
            for (int i = 0; i                 System.out.print (interfaces [i] .getSimpleName () + ",");
            }
            System.out.println (interfaces [interfaces.length - 1] .getSimpleName ());
        }
    }
}

Test test class: ArrayList

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
 
public class ClassInfoTest {
    
    private Class clazz ;
    
    private String className = "java.util.ArrayList";
    
    / **
    * ForName () is a method to obtain a reference to the Class object.
    String * It is a text that contains the name of the target class as input parameters, returns a reference to a Class object.
    * /
    @Before
    public void before () {
        try {
            clazz = Class.forName (className);
        } Catch (ClassNotFoundException e) {
            e.printStackTrace ();
        }
    }
    
    @After
    public void after () {
        clazz = null;
    }
    
    @Test
    public void testGetName () {
        ClassInfo.printName (clazz);
    }
    
    @Test
    public void testPrintClassIntf () {
        ClassInfo.printClassIntf (clazz);
    }
 
}

Test Results

getName: java.util.ArrayList
getCanonicalName: java.util.ArrayList
getSimpleName: ArrayList
ArrayList extends AbstractList implements List, RandomAccess, Cloneable, Serializable

Constructor
Constructor class is an ordinary Java class constructor abstraction. You can get the constructor represented by getConstructors Class class () method an array of objects, you can get the specified parameter type constructor by getConstructor (Class ... ParameterTypes). You can construct an instance of an object by newInstance (Object ... initargs) method. Note: Parameter newInstance () method and to getConstructor () method parameters correspond. For example getConstructor (String.class) --- getInstance ( "Jack").

The following tests were assuming we get a class byte from disk or network, that the package name of this class (reflcet) and class name (Reflect) and associated field name and a method name, and through the heat load is already loaded to the project.

method.invoke () will be mentioned in the Method below.

 Test category

package reflect;
 
/ **
 * @description Runtime class acquired
 * @author Administrator
 * /
public class Reflect {
    
    public int id;
    private String name;
    
    public Reflect () {
        this.name = "Tom";
    }
    
    public Reflect (String name) {
        this.name = name;
    }
    
    public Reflect (int id, String name) {
        this.id = id;
        this.name = name;
    }
    
    public void setName (String name) {
        this.name = name;
    }
    
    public String getName () {
        return name;
    }
    
    @SuppressWarnings ( "Unused")
    private void setId (int id) {
        this.id = id;
    }
    
    public int getId () {
        return id;
    }
    
    @Override
    public String toString () {
        return "id:" + id + ", name:" + name;
    }
 
}

 Test category

import static org.hamcrest.Matchers *.;
import static org.junit.Assert *.;
 
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
 
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
 
public class ReflectTest {
    
    < ?> Class clazz;
    
    / **
    * ClassName = "package name. Class name"
    * /
    String className = "reflect.Reflect";
    
    @Before
    public void before () {
        try {
            clazz = Class.forName (className);
        } Catch (ClassNotFoundException e) {
            e.printStackTrace ();
        }
    }
    
    @After
    public void after () {
        clazz = null;
    }
    
    @Test
    public void testConstructor () {
        try {
            / **
            * Get the no-argument constructor
            * /
             Constructor constructor = clazz.getConstructor ();
            Object obj = constructor.newInstance ();
            Method method = clazz.getMethod ( "getName");
            assertThat ((String) method.invoke (obj), containsString ( "Tom"));
            / **
            * Get the parameterized constructor
            * /
            constructor = clazz.getConstructor (String.class);
            obj = constructor.newInstance ( "Jack");
            assertThat ((String) method.invoke (obj), containsString ( "Jack"));
            / **
            * Get more parameters Constructor
            * /
            constructor = clazz.getConstructor (int.class, String.class);
            obj = constructor.newInstance (6, "Rose");
            method = clazz.getMethod ( "toString");
            assertThat ((String) method.invoke (obj), allOf (containsString ( "id: 6"), containsString ( "name: Rose")));
        } Catch (NoSuchMethodException e) {
            e.printStackTrace ();
        } Catch (SecurityException e) {
            e.printStackTrace ();
        } Catch (InstantiationException e) {
            e.printStackTrace ();
        } Catch (IllegalAccessException e) {
            e.printStackTrace ();
        } Catch (IllegalArgumentException e) {
            e.printStackTrace ();
        } Catch (InvocationTargetException e) {
            e.printStackTrace ();
        }
        
    }
    
}

Field

Field class is an ordinary Java class called attributes or abstract field. () Method can be obtained through the Class class getFields array of objects representing the fields to get to the object field of the given name by getField (String name), if the field modifier is private or protected, then getField () method throws java .lang.NoSuchFieldException exception. For non-public property is set, you can use getDeclaredField () method, and call setAccessible (true), so that the properties can be obtained.


Test Methods

@Test
public void testField () {
    try {
        / **
        * Class Class newInstance () method calls the default constructor to create an instance of an object
        * /
        Object obj = clazz.newInstance ();
        Method method = clazz.getMethod ( "getName");
        assertThat ((String) method.invoke (obj), containsString ( "Tom"));
        / **
        * Set the value of private property
        * /
        Field field = clazz.getDeclaredField ( "name");
        field.setAccessible (true);
        field.set (obj, "Jack");
        assertThat ((String) method.invoke (obj), containsString ( "Jack"));
        / **
        * Set the value of public property
        * /
        field = clazz.getField ( "id");
        field.setInt (obj, 9);
        method = clazz.getMethod ( "getId");
        assertThat (String.valueOf (method.invoke (obj)), containsString ( "9"));
    } Catch (InstantiationException e) {
        e.printStackTrace ();
    } Catch (IllegalAccessException e) {
        e.printStackTrace ();
    } Catch (NoSuchMethodException e) {
        e.printStackTrace ();
    } Catch (SecurityException e) {
        e.printStackTrace ();
    } Catch (IllegalArgumentException e) {
        e.printStackTrace ();
    } Catch (InvocationTargetException e) {
        e.printStackTrace ();
    } Catch (NoSuchFieldException e) {
        e.printStackTrace ();
    }
}

Method

Method class is an ordinary Java class method of abstraction. () Method can obtain representation by Class Class getMethods array of objects by getMethod (String name, Class ... ParameterTypes) ways to get the method names and method parameter types of methods of an object, if the method is modified character is private or protected, getMethod () method throws an exception java.lang.NoSuchMethodException. For non-public methods, you can getDeclaredMethod () method, and call setAccessible (true), so that the method can be obtained. Call method.invoke (Object obj, Object ... args) method to achieve the object obj method method invocation parameters args. And the same token constructor, getMethod () method and invoke methods to correspond. For example getMethod ( "setName", String.class) --- invoke (obj, "Rose").

Test Methods

@Test
public void testMethod () {
    try {
        / **
        * Public call no parametric method
        * /
        Object obj = clazz.newInstance ();
        Method method1 = clazz.getMethod ( "getName");
        assertThat ((String) method1.invoke (obj), containsString ( "Tom"));
        / **
        * Call a method of public participation
        * /
        Method method2 = clazz.getMethod ( "setName", String.class);
        method2.invoke (obj, "Jack");
        assertThat ((String) method1.invoke (obj), containsString ( "Jack"));
        / **
        * Call a Senate Private method
        * /
        Method method3 = clazz.getDeclaredMethod ( "setId", int.class);
        method3.setAccessible (true);
        method3.invoke (obj, 5);
        Method method = clazz.getMethod ( "getId");
        assertThat (String.valueOf (method.invoke (obj)), containsString ( "5"));
    } Catch (InstantiationException e) {
        e.printStackTrace ();
    } Catch (IllegalAccessException e) {
        e.printStackTrace ();
    } Catch (NoSuchMethodException e) {
        e.printStackTrace ();
    } Catch (SecurityException e) {
        e.printStackTrace ();
    } Catch (IllegalArgumentException e) {
        e.printStackTrace ();
    } Catch (InvocationTargetException e) {
        e.printStackTrace ();
    }
}

Class method extractor
When developers to learn a class (eg: ArrayList), the realization of a class definition by browsing the source code or its JDK documentation can only be found in this class definition is defined or overwritten methods. But for developers, probably dozens more useful methods are followed Chengzi Ji class. To find these methods can be very tedious and time consuming. Fortunately, reflection provides a method, enables developers to write a simple tool can automatically show the complete interface. It works as follows:

/ **
 * @description Class method extractor
 * @param Clazz
 * /
public static void printClassInfo (Class clazz) {
    Pattern pattern = Pattern.compile (( "\\ w + \\."));
     Constructor [] constructors = clazz.getConstructors ();
    Method [] methods = clazz.getMethods ();
    Field [] fields = clazz.getDeclaredFields ();
    for (Field field: fields) {
        System.out.println (pattern.matcher (field.toGenericString ()) replaceAll ( "").);
    }
    for ( Constructor constructor: constructors) {
        System.out.println (pattern.matcher (constructor.toGenericString ()) replaceAll ( "").);
    }
    for (Method method: methods) {
        System.out.println (pattern.matcher (method.toGenericString ()) replaceAll ( "").);
    }
}

 Test test method: ArrayList

@Test
public void testPrintClassInfo () {
    try {
        ClassInfo.printClassInfo (Class.forName ( "java.util.ArrayList"));
    } Catch (ClassNotFoundException e) {
        e.printStackTrace ();
    }
}

 Test Results:

private static final long serialVersionUID
private static final int DEFAULT_CAPACITY
private static final Object [] EMPTY_ELEMENTDATA
private static final Object [] DEFAULTCAPACITY_EMPTY_ELEMENTDATA
transient Object [] elementData
private int size
private static final int MAX_ARRAY_SIZE
public ArrayList (Collection )
public ArrayList ()
public ArrayList (int)
public boolean add (E)
public void add (int, E)
public boolean remove (Object)
public E remove (int)
public E get (int)
public Object clone ()
public int indexOf (Object)
public void clear ()
public boolean contains (Object)
public boolean isEmpty ()
public Iterator iterator ()
public int lastIndexOf (Object)
public void replaceAll (UnaryOperator )
public int size ()
public List subList (int, int)
public T [] toArray (T [])
public Object [] toArray ()
public Spliterator spliterator ()
public boolean addAll (int, Collection )
public boolean addAll (Collection )
public void forEach (Consumer )
public E set (int, E)
public void ensureCapacity (int)
public void trimToSize ()
public ListIterator listIterator (int)
public ListIterator listIterator ()
public boolean removeAll (Collection )
public boolean removeIf (Predicate )
public boolean retainAll (Collection )
public void sort (Comparator )
public boolean equals (Object)
public int hashCode ()
public String toString ()
public boolean containsAll (Collection )
public final void wait () throws InterruptedException
public final void wait (long, int) throws InterruptedException
public final native void wait (long) throws InterruptedException
public final native Class getClass ()
public final native void notify ()
public final native void notifyAll ()
public default Stream stream ()
public default Stream parallelStream ()

JVM
Reflection and no magic. When dealing with a reflection by an unknown type of object, JVM simply checking the object. Therefore, .class files for the JVM that class must be available: either on the local machine, or can be obtained through the network. Have been for reflection, .class file is run when opening and checking .class file at compile time to time can not get it.

application
Suppose developers get a bunch of bytes from a disk file, or a network connection, and was told that those bytes represent a class. Since this class only appeared long after the program is compiled, if you want to use this class, we need to use emission mechanism. Thermal load belongs to this scene.

Get the class information at run time another scene, developers want to provide the ability to create and run objects on remote platforms across the network. This is called Remote Method Invocation (RMI) which allows a Java program on multiple machines distributed objects.

Write their own framework, developers will certainly be used in reflection, a very simple example is the event bus and annotation framework.


to sum up

Reflection is very flexible in daily development, reflecting less caution, reflecting the expense of performance. When writing the frame, the reflection is not shy about using reflection to help their own hand at a critical time.
     
         
       
         
  More:      
 
- DDOS Attacks and Prevention (Linux)
- Flow control message transmission between RAC (Database)
- CentOS and RHEL installation under GAMIT10.6 (Linux)
- ActiveMQ5.11.1 and JDK version matching relation (Linux)
- Oracle creates split and splitstr functions (Database)
- Java reflection technology explain (Programming)
- Use Aptik Battery Monitor monitoring Ubuntu laptop battery usage (Linux)
- Linux argument references and command substitution (Linux)
- Linux software firewall ACL match point optimization (Linux)
- Linux tmux tcpdump summary (Linux)
- Adjust the size of the hard disk VirtualBox (Linux)
- MySQL Parameter Tuning Best Practices (Database)
- Oracle 11g RAC root.sh execution error second node failure example (Database)
- Golang environment configuration recommendations (Linux)
- IPTABLES configuration steps under Linux (Linux)
- MySQL InnoDB table --BTree basic data structures (Database)
- Alternative methods of intrusion bundled executable file new thinking (Linux)
- To resolve Ubuntu 14.04 Unity Desktop Environment Login freeze problem (Linux)
- VPN built on CentOS (Server)
- VirtualBox CentOS is configured as a local disk mirroring software source (Linux)
     
           
     
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.