Java Reflection Mechanism (i)--instantiate an object with a reflection mechanism

Source: Internet
Author: User
Tags object object throw exception

One, Java has a very prominent dynamic correlation mechanism: Reflection, used in Java refers to we can at runtime loading, detection, using the classes is completely unknown during compilation. In other words, a Java program can load a runtime to know the name of a class, learn its full construct (but not including the methods definition), and generate its object entities, or set values on its fields, or evoke its methods. (That's what the Niang library says)


Second, this article mainly introduces the reflection mechanism to instantiate a class object, and then call its methods. This article mainly introduces two ways, the first is through the constructor to instantiate, the second is through the Class<t> class Newnstance () method to instantiate, the following I will show through the code:

1, first I built a person class as a test:

Package com.reflect.test;/** * @author Lin Yu peng * @description Test * @create 2014-11-27 PM 9:34:00 *  */public class Person { private int age;private string name;public person () {}public person (String name) {this.name = name;} public person (int age, String name) {this.age = Age;this.name = name;} public void Setage (int.) {this.age = age;} public void SetName (String name) {this.name = name;} public int getage () {return age;} Public String GetName () {return name;}}


2. Through the constructor function:

Package Com.reflect.test;import Java.lang.reflect.constructor;import java.lang.reflect.InvocationTargetException; Import java.lang.reflect.method;/** * @author Lin Yu * @description reflection mechanism, instantiating objects through constructors * @create 2014-11-27 pm 9:32:05 * */publi  C class Reflectconstructor {public static void main (string[] args) {Person person = new person (); try {class<?> cls = Class.forName (Person.getclass (). GetName ());//parameter type class<?>[] params = {Integer.type, string.class};// Parameter value object[] values = {, "Kroc"};//constructs a constructor with two parameters constructor<?> constructor = cls.getdeclaredconstructor (params) ;//Based on the constructor, the incoming value is generated as an instance of object object = Constructor.newinstance (values); Method getage = Cls.getdeclaredmethod ("Getage"); Method getName = Cls.getdeclaredmethod ("GetName"); System.out.println ("getage =" + (Integer) Getage.invoke (object)); System.out.println ("GetName =" + (String) Getname.invoke (object));} catch (ClassNotFoundException e) {e.printstacktrace (); System.out.println ("ClassNotFoundException");} catch (NosuchmethodexcEption e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (SecurityException e) {//Todo auto-generated cat CH Blocke.printstacktrace ();} catch (Instantiationexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (Illegalaccessexception e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (IllegalArgumentException e) {//Todo auto-generated cat CH Blocke.printstacktrace ();} catch (InvocationTargetException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}
You can see the code, the following two lines are more important, the first line is to get a constructor by the number of parameters, remember that the number and type of parameters passed in the person inside the constructor of the match, and the parameter type and the parameter value of the type of values, I'm going to enclose it in a params and values.

Constructs a constructor with two parameters constructor<?> constructor = Cls.getdeclaredconstructor (params);//Based on the constructor, the incoming value is generated as an instance of object object = Constructor.newinstance (values);

The results of the operation are as follows:




3. The second method is initialized by the Newnstance () method of the Class<t> class:

Package Com.reflect.test;import java.lang.reflect.invocationtargetexception;import java.lang.reflect.method;/** * @ Author Lin Yu Peng * @description reflection mechanism via newinstance () instantiate object * @create 2014-11-27 PM 9:41:01 * */public class ReflectMethod {public static void Main (string[] args) {Person person = new person (); try {class<?> cls = Class.forName (Person.getclass (). GE Tname ());//Generate an instance, call the default parameterless constructor Object object = Cls.newinstance (); Method setName = Cls.getdeclaredmethod ("SetName", String.class); Method setage = Cls.getdeclaredmethod ("Setage", Integer.type); Setname.invoke (object, "Kroclin"); Setage.invoke ( object, 20); Method getage = Cls.getdeclaredmethod ("Getage"); Method getName = Cls.getdeclaredmethod ("GetName"); System.out.println ("getage =" + (Integer) Getage.invoke (object)); System.out.println ("GetName =" + (String) Getname.invoke (object));} catch (ClassNotFoundException e) {e.printstacktrace (); System.out.println ("ClassNotFoundException");} catch (Nosuchmethodexception e) {//TODO auto-generated catch BLocke.printstacktrace ();}  catch (SecurityException e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (Instantiationexception e) {// TODO auto-generated catch Blocke.printstacktrace ();} catch (Illegalaccessexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch ( IllegalArgumentException e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (InvocationTargetException E {//TODO auto-generated catch Blocke.printstacktrace ();} }}
The code knows that, in fact, using newinstance () is the default parameterless constructor for calling person, so it's essentially the same way.

Operation Result:


Three, about the reflection mechanism, there are many things that can be done, above I for a simple display similar to getname these method names are written dead, in fact, can also be reflected to get the method name, including the method of return type Ah, throw exception, etc. can be obtained through the reflection mechanism. Later on there is time to write about the Java reflection mechanism of the article sharing, for this if there is a wrong write or what better suggestions trouble comment exchange.

Java Reflection Mechanism (i)--instantiate an object with a reflection mechanism

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.