Invoking a class's constructors and general functions using the Java Reflection Mechanism __ block chain

Source: Internet
Author: User

Preface read the Document of Master Houtie, it is very rewarding, hehe (Mt always laughs like this ....) )

 package test; Import Java.lang.reflect.Constructor; Import java.lang.reflect.InvocationTargetException; Import Java.lang.reflect.Method; Import Test2. TestClass; * * * Invoke TestClass Constructors and general functions via reflection/public class Reflection2 {public static void main (string[] args) {* * in reflection dynamic machine There are two approaches to the system, one for "no ctor" and one for "ctor with parameters". * * SYSTEM.OUT.PRINTLN ("Invoke The default ctor:"); try {Class TestClass1 = Class.forName ("Test2. TestClass "); Call the default constructor, which can be invoked directly with the TestClass Object obj = testclass1.newinstance (); System.out.println (obj); catch (ClassNotFoundException e) {//TODO auto-generated catch block E.printstacktrace ();} catch (Instantiationexcepti On e) {//Todo auto-generated catch block e.printstacktrace (); \ catch (Illegalaccessexception e) {//Todo Auto-generate D Catch block E.printstacktrace (); } System.out.println ("********************************"); System.out.println ("Invoke the ctor with Parameters:"); try {Class testClass2 = Class.forName ("Test2. TestClass "); First prepare a class[] to doThe parameter type for ctor (this example is specified as an int and a String), class[] PType = new class[] {int.class, class.forname ("java.lang.String")}; Call PType as a variable of getconstructor (), obtain an exclusive ctor constructor ctor = Testclass2.getconstructor (PType); Prepare a object[] as the ctor argument value object[] obj = new object[] {2, "anybody"}; Invoke the above exclusive ctor newinstance () Object result = Ctor.newinstance (obj); SYSTEM.OUT.PRINTLN (result); catch (SecurityException e) {//TODO auto-generated catch block E.printstacktrace ();} catch (Nosuchmethodexception e) {//TODO auto-generated catch block E.printstacktrace ();} catch (ClassNotFoundException e) {//TODO auto-generated catch block E.printstacktrace ();} catch (Illegalargumentexcepti On e) {//Todo auto-generated catch block e.printstacktrace (); \ catch (Instantiationexception e) {//Todo Auto-generate D Catch block E.printstacktrace (); catch (Illegalaccessexception e) {//TODO auto-generated catch block E.printstacktrace ();} catch (Invocationtargetexce Ption e) {//TODO auto-generated catch blocK E.printstacktrace (); } System.out.println ("********************************"); System.out.println ("Invoke a function of TestClass, eg SetName:"); try {Class testClass3 = Class.forName ("Test2. TestClass "); Prepare a class[] as the parameter type of the calling function (in this case, String)///If there are multiple arguments, it needs to be declared as class[] Class pTypes = Class.forName ("java.lang.String"); Call GetMethod () with ptypes as the argument, obtaining a specific Method object//The function name setname and parameter types specified in GetMethod to be invoked ptypes methods = Testclass3.getmethod ("SetName", pTypes); Prepares an object to place the argument, or directly declares as a string aname = new String ("Bao"); Object aname = "Baobao"; This declares a TestClass object because the SetName needs to modify the name of the data member//If there is no object in the SetName. AStudent is the default value of the ID 1,name to somebody testclass astudent = new TestClass (); The Invoke () of the specific method object mentioned above is the SetName () Method.invoke (AStudent, aname) in TestClass; System.out.println (astudent); catch (ClassNotFoundException e) {//TODO auto-generated catch block E.printstacktrace ();} catch (SecurityException e) {//TODO auto-generated catch block E.printstacktrace ();}catch (Nosuchmethodexception e) {//TODO auto-generated catch block E.printstacktrace ();} catch (Illegalargumentexceptio n e) {//Todo auto-generated catch block E.printstacktrace (), catch (Illegalaccessexception e) {//Todo auto-generated Catch block E.printstacktrace (); catch (InvocationTargetException e) {//TODO auto-generated catch block E.printstacktrace ();}} }

TestClass for testing:

Package test2; Import java.util.*; public class TestClass implements comparable {private int id; private String name; public TestClass () {this.id = 1; . Name = "Somebody"; public TestClass (int ID, String name) {this.id = id; this.name = name;} public void setId (int id) {this.id = ID;} PU Blic void SetName (string name) {this.name = name;} public String GetName () {return this.name;} public int getId () {RET Urn this.id; public int compareTo (Object obj) {return 0;} public String toString () {return "<" + ID + ">" + "<" +name+ ">" ; } }

Run Result:

Invoke the default ctor:
<1> <somebody>
********************************
invoke the ctor with Parameters:
<2> <anybody>
********************************
Invoke a function of TestClass, eg SetName:
<1> <baobao>

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.