Java Black Magic-reflection mechanism -02-calling other class methods through Java reflection

Source: Internet
Author: User

 PackageCom.aaron.reflect;ImportJava.lang.reflect.Method;Importjava.lang.reflect.InvocationTargetException;/*** Created by IntelliJ idea. * File:TestRef.java * user:leizhimin * date:2008-1-28 14:48:44*/  Public classTestref {//Direct foo.outinfo (); You can also call that custom method Public Static voidMain (String args[])throwsnosuchmethodexception, Illegalaccessexception, invocationtargetexception { foo foo  = new foo ("This one Foo Object!") "); //a real object of a class       class<?> clazz =Foo.getclass (); ? Any type= Clazz.getdeclaredmethod ("Outinfo"); The custom method, M1, is the method name m2 = Clazz.getdeclaredmethod ("setmsg", String.class);//set method m3 = clazz.getd Eclaredmethod ("getmsg"); The Get method//The following statement outputs--------This is the test class M1.invoke (foo) that tests the Java reflection; The message can be printed without print, and the breakpoint Foo is a really Foo class object M2.invoke (foo, "Reset msg info!"). ");         does not output String msg = (string) m3.invoke (foo); SYSTEM.OUT.PRINTLN (msg);    Reset MSG Information! }//Method name. Invoke (The object of the Class);}     Class Foo {private String msg;     Public Foo (String msg) {this.msg = msg;     } public void Setmsg (String msg) {this.msg = msg;     } public String getmsg () {return msg;     } public void Outinfo () {System.out.println ("This is the test class for testing Java reflection"); } }
 PackageCom.aaron.reflect;Importjava.lang.reflect.InvocationTargetException;ImportJava.lang.reflect.Method; Public classDemo5 { Public Static voidMain (string[] args) { Class <?> herosclass = Heros. class; //get instances of class classes//New Herosclass () cannot be new        Try{//the value of Herosclass inside the breakpoint is class Com.aaron.reflect.HerosMethod m1 = Herosclass.getmethod ("SetName", String.class); Method m2= Herosclass.getmethod ("GetName"); Method M3 = Herosclass.getmethod ("Say");            //or Object userInfo = herosclass.newinstance ()         Heros userInfo = (Heros) herosclass.newinstance ();//the UserInfo value is not the same as the previous object valueM1.invoke (UserInfo, "Shadow Demon");//called the set method here.SYSTEM.OUT.PRINTLN ("Call set Method:" +userinfo);//output [Heros [Name= Shadow Demon, Type=null,camp=0]]System.out.println ("Call Get Method:" +m2.invoke (UserInfo));//Call get method: Shadow Demon           M3.invoke (userInfo); //You can call your own method.}Catch(Exception e) {e.printstacktrace (); }    }} PackageCom.aaron.reflect; Public classHeros {PrivateString name;//name    PrivateString type;//type    Private intCamp//          PublicHeros () {} PublicHeros (string name, String type,intCamp) {        Super();  This. Name =name;  This. Type =type;  This. Camp =Camp; }     Public voidsay () {System.out.println ("You can call your own method."); }      PublicString GetName () {returnname; }      Public voidsetName (String name) { This. Name =name; }      PublicString GetType () {returntype; }      Public voidsetType (String type) { This. Type =type; }      Public intGetcamp () {returnCamp; }      Public voidSetcamp (intCamp) {         This. Camp =Camp; } @Override PublicString toString () {return"Heros [\ n name=" + name + ", \ n type=" + type + ", \ n camp=" + Camp + "\ n]"; }     }

Java Black Magic-reflection mechanism -02-calling other class methods through 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.