Reflection in Java and Java reflection

Source: Internet
Author: User

Reflection in Java and Java reflection
Java reflection API

Java reflectionIt refers to the process in which attributes and methods of a class can be obtained or behavior of a class can be modified during runtime.

Java. lang. ClassClass provides many methods for getting metadata, checking and changing the behavior of the class runtime.

Java reflection mainly involves classes in the java. lang and java. lang. reflect packages.

Example of reflection Application Scenario java. lang. Class

Java. lang. Class provides the following two functions:

Common Methods for java. lang. Class classes
Method Description
1) public String getName () Returned Class Name
2) public static Class forName (String className) throws ClassNotFoundException Load Class and return Class Object
3) public Object newInstance () throws InstantiationException, IllegalAccessException Create an Instance Object
4) public boolean isInterface () Determine whether it is an interface
5) public boolean isArray () Determine whether it is an array
6) public boolean isPrimitive () Determine whether it is the original data type
7) public Class getSuperclass () Returns the parent Class reference.
8) public Field [] getDeclaredFields () throws SecurityException Returns an array of member attribute fields of a class.
9) public Method [] getDeclaredMethods () throws SecurityException Method array of the returned class
10) public Constructor [] getDeclaredConstructors () throws SecurityException Returns the constructor array of the class.
11) public Method getDeclaredMethod (String name, Class [] parameterTypes) throws NoSuchMethodException, SecurityException Return the method of the specified parameter type in the class.
How to obtain Class objects

There are three methods:

ForName () method example

It can be used for dynamic loading. You can use this method when you know the full-qualified name of the class. Note that this method is not applicable to the raw data type;

package tmp;class Simple{}public class Test{    public static void main(String args[]) throws ClassNotFoundException    {        Class<?> c = Class.forName("tmp.Simple");        System.out.println(c.getName());        System.out.println(c.getSimpleName());    }}
Tmp. Simple
Simple

Example of the getClass () method:

Obtain a Class object from an Instance Object

package tmp;class Simple{}public class Test{    void printName(Object obj)    {    }    public static void main(String args[])    {        Simple s = new Simple();        Class<? extends Object> c = s.getClass();        System.out.println(c.getName());        System.out.println(c.getSimpleName());    }}
Tmp. Simple
Simple

. Class syntax example

The class name can also be applied to the original data type, as shown below:

package tmp;public class Test{    public static void main(String args[])    {        Class<Boolean> c = boolean.class;        System.out.println(c.getName());        Class<Test> c2 = Test.class;        System.out.println(c2.getName());    }}
Boolean
Tmp. Test determine the type of the Class Object

You can use the following methods to determine the type of A Class Object:

1) public boolean isInterface ():Corresponding interface?
2) public boolean isArray ():Array?
3) public boolean isPrimitive ():Corresponds to the original data type?

Sample Code:

package tmp;class Simple{}interface My{}public class Test{    public static void main(String args[])    {        try        {            Class<?> c = Class.forName("tmp.Simple");            System.out.println(c.isInterface());            Class<?> c2 = Class.forName("tmp.My");            System.out.println(c2.isInterface());        }        catch (Exception e)        {            System.out.println(e);        }    }}
False
True: creates an instance object through reflection

There are two methods:

Therefore, the second method is generally more widely used than the first method.

Example of a Class Object calling the newInstance () method

package tmp;class Simple{    void message()    {        System.out.println("Hello Java");    }}public class Test{    public static void main(String args[])    {        try        {            Class<?> c = Class.forName("tmp.Simple");            Simple s = (Simple) c.newInstance();            s.message();        }        catch (Exception e)        {            System.out.println(e);        }    }}
Hello Java

Example of the Constructor object calling newInstance () method

Note that the specified constructor can be obtained based on the input parameter type, and the access permission restriction of the constructor can be changed.

package tmp;import java.lang.reflect.Constructor;class Simple{    private String msg;    void message()    {        System.out.println("Hello Java," + msg);    }    private Simple(String s){        this.msg = s;    }}public class Test{    public static void main(String args[])    {        try        {            Class<?> c = Class.forName("tmp.Simple");            Constructor<?> con = c.getDeclaredConstructor(String.class);            con.setAccessible(true);            Simple s = (Simple) con.newInstance("...");            s.message();        }        catch (Exception e)        {            System.out.println(e);        }    }}
Hello Java,... call the private method through reflection

Through reflection, we can call private methods of other classes, mainly involving java. lang. Class and java. lang. reflect. Method classes;

The setAccessible Method and invoke Method of the Method class are used. The former modifies the access permission and the latter calls the Method.

Example of calling a private method with parameters:

package tmp;import java.lang.reflect.Method;class A{    private void cube(int n)    {        System.out.println(n * n * n);    }}class Test{    public static void main(String args[]) throws Exception    {        Class<A> c = A.class;        Object obj = c.newInstance();        Method m = c.getDeclaredMethod("cube", new Class[]{ int.class });        m.setAccessible(true);        m.invoke(obj, 4);    }}
About javap tools

The javap command can be used to disassemble the java bytecode file to display the field attributes, constructor methods, and common method information in the class file;

Instructions for use:

Javap java. lang. Object example

Javap-c Test example:

Write a simple Test class, as shown below:

package tmp;class Simple{}public class Test{    public static void main(String args[])    {        System.out.println("Hello");    }}

Enter javap-c Test:

References

It is basically a translation and has made a small part of changes.

Http://www.javatpoint.com/java-reflection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.