"Turn" a very good example of Java reflection

Source: Internet
Author: User

Transfer from http://www.douban.com/note/306848299/

Original:

1, the conceptual reflection meaning of Java reflection: You can get a running Java object. 2, the functionality of Java reflection1) to determine the class to which the run-time object belongs2) to determine the member variables and methods that are available at run time objects3A method that can even be called to private by reflection4) to generate a dynamic proxy3, classes that implement Java reflection1class: It represents classes and interfaces in a running Java application2Field: Provides information about the properties of a class or interface, as well as the dynamic access rights to it3Constructor: Provides information about a single construction method of a class and access to it4methods: Provides information about a method in a class or interface Note: Class is the most important feature class in Java reflection, all information that gets the object (including: Method/Properties/Construction Method/access) requires it to implement4, the steps to write the Java Reflector program:1You must first get a class object for example: Class C1= Test.class; Class C2=class.forname ("Com.reflection.Test"); Class C3=NewTest (). GetClass (); 2) Then call the methods in the class object to get the properties/methods of a classstructure of the construction method Note: If you want to be able to get the methods in the class normallyPropertiesthe construction method should focus on the following reflection class Field Constructor Method Example: This program example tells you how to operate class/field/constructor/class, such as Java reflection related to method Packagecom.reflection; ImportJava.lang.reflect.Constructor; ImportJava.lang.reflect.Field; Importjava.lang.reflect.InvocationTargetException; ImportJava.lang.reflect.Method; ImportJava.lang.reflect.Modifier;  Public classtestreflection {PrivateString username; PrivateString password; Private int[] age;  Public voidSetusername (String username) { This. Username =username; }Private voidSetPassword (String password) { This. Password =password; } Public Static voidTEST01 ()throwsclassnotfoundexception {Class C1= Testreflection.class; Class C2= Class.forName ("Com.reflection.TestReflection"); //gets the specified package nameString package01 =c1.getpackage (). GetName (); String PACKAGE02=c2.getpackage (). GetName (); System.out.println ("PACKAGE01 =" +package01); System.out.println ("PACKAGE02 =" +package02); //gets the modifier for the class    intMoD =c1.getmodifiers (); String modifier=modifier.tostring (mod); System.out.println ("Modifier =" +modifier); //gets the fully qualified name of the specified classString ClassName =C1.getname (); System.out.println ("ClassName =" +className); //gets the parent class of the specified classClass Superclazz =C1.getsuperclass (); String Superclazzname=Superclazz.getname (); System.out.println ("Superclazzname =" +superclazzname); //get the implemented interfaceClass[] Interfaces =c1.getinterfaces ();  for(Class t:interfaces) {System.out.println ("Interfacesname =" +t.getname ()); }//gets the member variable of the specified classfield[] Fields =C1.getdeclaredfields ();  for(Field field:fields) {modifier= Modifier.tostring (Field.getmodifiers ());//get eachField's access modifier Class type= Field.gettype ();//gets the data type of the field that corresponds to theclass object String name= Field.getname ();//Get field name    if(Type.isarray ()) {//if it is an array type, special handling is requiredString Arrtype = Type.getcomponenttype (). GetName () + "[]"; System.out.println ("+ modifier +" "+ Arrtype +" "+ name +"; "); } Else{System.out.println ("+ modifier +" "+ Type +" "+name+ ";"); }}//get the constructor method of a classConstructor[] Constructors =c1.getdeclaredconstructors ();  for(Constructor constructor:constructors) {String name= Constructor.getname ();//constructor Method NameModifier = modifier.tostring (Constructor.getmodifiers ());//Get access ModifiersSystem.out.println ("" + modifier + "" + Name + "("); Class[] Paramtypes= Constructor.getparametertypes ();//get parameters in a constructor method     for(inti = 0; i < paramtypes.length; i++) {if(I > 0) {System.out.print (","); }if(Paramtypes[i].isarray ()) {System.out.println (paramtypes [I].getcomponenttype (). GetName ()+"[]"); } Else{System.out.print (Paramtypes[i].getname ()); }} System.out.println (");"); }//Get member MethodsMethod[] Methods =C1.getdeclaredmethods ();  for(Method method:methods) {modifier=modifier.tostring (Method.getmodifiers ()); Class ReturnType= Method.getreturntype ();//gets the return type of the method    if(Returntype.isarray ()) {String Arrtype=Returntype.getcomponenttype (). GetName ()+"[]"; System.out.print ("" +modifier+ "" + Arrtype + "" +Method.getname ()+ "("); } Else{System.out.print ("+ modifier +" "+Returntype.getname ()+ "" + method.getname () + "("); } class[] Paramtypes=method.getparametertypes ();  for(inti = 0; i < paramtypes.length; i++) {if(I > 0) {System.out.print (","); }if(Paramtypes[i].isarray ()) {System.out.println (paramtypes [I].getcomponenttype (). GetName ()+"[]"); } Else{System.out.print (Paramtypes[i].getname ()); }} System.out.println (");"); }} Public Static voidtest02 ()throwsinstantiationexception, Illegalaccessexception, SecurityException, Nosuchmethodexception, IllegalArgumentException, InvocationTargetException {//reflection Call method, which can be called by the Invoke method of method class to implement dynamic methods.//Public object Invoke (Object obj, object ... args)//The first parameter represents an object//The second parameter represents a parameter on the execution method//if the reflection is to invoke a private method of the class, the Mehtod object corresponding to the private method is firstCall Setaccessible (true) Class C1= Testreflection.class; testreflection T1= (testreflection) c1.newinstance ();//use reflection to createObject System.out.println of the built class ("Username = =" +t1.username); System.out.println ("Password = =" +T1.password); Method Method= C1.getdeclaredmethod ("Setusername", String.class); Method.invoke (T1,"Learning from Java reflection"); System.out.println ("Username = =" +t1.username); Method= C1.getdeclaredmethod ("SetPassword", String.class); Method.setaccessible (true); Method.invoke (T1,"Reflection performs a method of a private adornment"); System.out.println ("Password = =" +T1.password); } Public Static voidMain (string[] args)throwsclassnotfoundexception, SecurityException, IllegalArgumentException, Instantiationexception, Illegalaccessexception, Nosuchmethodexception, invocationtargetexception {//test01 ();test02 (); }}

"Turn" a very good example of 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.