The reflection mechanism of Java

Source: Internet
Author: User

Class reflection objects describe the semantic structure of a class, and you can get a reflection object of a class element such as a constructor, member variable, method class from a class object, and manipulate the target object programmatically by reflecting the object. The Reflective object class is defined in the Java.lang.reflect package, consisting mainly of three main reflection classes: Constructor, Method, Field.

Constructor

The class constructor reflects the class, and the Class.getdeclaredconstructors () method allows you to get an array of reflected objects for all constructors of the class. In addition, you can also pass class. The Getdeclaredconstructor (Class ... parametertypes) method gets the reflection object for the concrete constructor.

The class has a primary method Newinstance (object [] Initargs) through which you can create an instance of a class object

Attention:

The class class has 4 methods to get the constructor reflection object, where getconstructors is used to get all the exposed list of constructed methods, and GetConstructor gets the exposed construction method based on the parameter type. The other two correspondence methods Getdeclaredconstructors and Getdeclaredconstructor are similar, except that they get the constructor method that is actually declared in the class, ignoring the constructor that inherits from the parent class (including the overridden constructor)

Method

class method of reflection class, through class. The Getdeclaredmethods () method gets all the methods of the class reflection class object array method[]. In addition, you can get the concrete method of the class by Class.getdeclaredmethod (String name, class ... parametertypes) method to reflect the class object.

The main method of the class invoke (Object Obj,object[]args)

Attention:

There are also 4 methods in the class class to get the method reflection object, where GetMethods is used to get all the exposed method lists, and GetMethod gets the public method based on the parameter type. The other two correspondence methods Getdeclaredmethods and Getdeclaredmethod are similar, except that they get the constructor method that is actually declared in the class, ignoring the constructor that inherits from the parent class (including the overridden method)

Field

Class member Variable reflection class, through class. The Getdeclaredfields () method can get an array of class-member variable reflection objects, through class. The Getdeclaredfield (String name) method can get the specific member variable of the class.

The main method of the class set (object Obj,object value) obj represents the target object

/*** Abstract Class--base class **/ Public Abstract classPerson { Public AbstractString getsex ();  Public voidintroduce () {System.out.println ("I am a person ..."); }}/******************* Gorgeous split-line ***********************//*** Subclass (Inherits Person Class) **/ Public classMansextendsPerson {PrivateString name = ""; Private intAge = 0; @Override PublicString Getsex () {//TODO auto-generated Method Stub        return"Man"; } @Override Public voidintroduce () {System.out.println ("I am a man ..."); }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }        /**set to Private*/@SuppressWarnings ("Unused")    PrivateString Say () {return"My name is" + name + "and I am" +Age ; } @SuppressWarnings ("Unused")    Private voidsetnameandage (String name, Integer age) {setName (name);    Setage (age); }}/******************* Gorgeous split-line *********************//*** Java Reflection Operation Step: * 1---get class object * 2---method to get Class object reflection object, variable reflection object **/ Public classReflecttest { Public Static voidOutputmethod (class<?>clazz) {        /**gets all the methods in the class (including methods inherited from the parent class)*/Method [] Methods=Clazz.getmethods ();  for(Method method:methods) {System.out.println ("All METHOD:" +method.getname ()); }        /**get methods declared in class (including methods to re-implement the parent class)*/Methods=Clazz.getdeclaredmethods ();  for(Method method:methods) {System.out.println ("Declared METHOD:" +method.getname ()); }    }         Public StaticMethod Outputmethod (class<?> clazz,string name,class<?> params[])throwsException {/**specific methods for obtaining declarations in class (including methods inherited by inheritance in the parent class)*/Method Method=Clazz.getdeclaredmethod (name, params); System.out.println ("Specific declared METHOD:" +method.getname ()); returnmethod; }             Public Static voidMain (String []args)throwsException {ClassLoader loader=Thread.CurrentThread (). Getcontextclassloader (); /**Get Class object*/Class<?> clazz = Loader.loadclass ("Com.qunar.reflect.Man"); /**constructing a Person object*/Man Mans=(man) clazz.newinstance (); /**gets the reflection object of the man's method*/Reflecttest.outputmethod (Clazz); System.out.println ("/*********************************/"); Method Method= Reflecttest.outputmethod (Clazz, "Setnameandage",NewClass[]{string.class, Integer.class}); /**allow calling private methods*/method.setaccessible (true); Method.invoke (man,Newobject[]{"Xiaolong", 28}); Method= Reflecttest.outputmethod (Clazz, "say",Newclass[]{}); /**allow calling private methods*/method.setaccessible (true); String Res= (String) Method.invoke (man,Newobject[] {}); System.out.println ("Reflect Invoke Result:" +res); }    }

The reflection mechanism of Java

Related Article

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.