Java Reflection mechanism

Source: Internet
Author: User

Java reflection mechanism--Get member variables & constructors
A member variable is an object of Java.lang.reflect.Field
1. Field class encapsulates operations on member variables
2, field[] fs = C.getfields () method gets the member variable field[] information for all public
3. C.getdeclaredfields gets the member variable information that the class declares itself
4. Field.gettype () Gets the class type of the member type
5, Field.getname () get the name of the member
Second, the constructor is the object of the Java.lang.Constructor class
1, through Class.getconstructor () get constructor[] All public construction method information
2, suggest getdeclaredconstructors () to get their own declaration of the construction method
3, Constructor.getname (): String
4, Constructor.getparametertypes (): class[]
Member variables are also objects, objects that are Java.lang.reflect.Field

1 ImportJava.lang.reflect.Constructor;2 ImportJava.lang.reflect.Field;3 ImportJava.lang.reflect.Method;4 5  Public classClassutil {6      Public Static voidprintmethedsmessage (Object obj) {7Class cs=Obj.getclass ();8Method []method =cs.getmethods ();9          for(Method meth:method) {TenSystem.out.print (Meth.getname () + "("); OneClass ptype[] =meth.getparametertypes (); A              for(Class type:ptype) { -System.out.print (Type.getname () + ","); -             } theSystem.out.println (")"); -         } -     } -      Public Static voidprintconmessage (Object obj) { +Class c=Obj.getclass (); -Constructor[] Con=c.getdeclaredconstructors (); +          for(Constructor constructor:con) { ASystem.out.print (constructor+ "("); atClass[]field =constructor.getparametertypes (); -              for(Class Ff:field) { -System.out.print (ff+ ","); -             } -System.out.println (")"); -         } in          -     } to}

Calling methods by reflection mechanism

1 Importjava.lang.reflect.InvocationTargetException;2 ImportJava.lang.reflect.Method;3 4  Public classClassmethod {5      Public Static voidMain (String arg[]) {6A a1=NewA ();7Class Cs=a1.getclass ();//to get the class type first8         Try {9Method m = Cs.getmethod ("Print",Newclass[]{});Ten             Try { One                 /* A * The corresponding parameter list -                  */ -M.invoke (NewA ());//reverse Call method using reflection mechanism the}Catch(Exception e) { - e.printstacktrace (); -             } -}Catch(Exception e) { + e.printstacktrace (); -         }  +     } A } at classa{ -      Public voidprint () { -System.out.println ("HelloWorld"); -     } -}

Understanding the nature of generics through reflection

1 ImportJava.lang.reflect.Method;2 Importjava.util.ArrayList;3 4  Public classfanxing {5 6      Public Static voidMain (string[] args) {7Arraylist<string> List1 =NewArraylist<string>();8ArrayList list =NewArrayList ();9List1.add ("HelloWorld");Ten         /* One * List1.add (20);//ToolTip error, indicating that eclipse is automatically compiled A          */ -Class cs =List1.getclass (); -Class No =List.getclass (); the         if(cs = =No) -System.out.println (true); -         /* - * The answer is true to indicate that the compiled collection is de-generalized + * Generics for Java collections, to prevent input errors, only valid at compile time, bypass compilation is invalid - * We can use the reflection of the method to operate, bypassing the compilation +          */ A         Try { at@SuppressWarnings ("Unchecked") -Method m = Cs.getmethod ("Add", Object.class); -M.invoke (List1, 20);//Bypassing the compilation bypasses generics - System.out.println (list1); -}Catch(Exception e) { - e.printstacktrace (); in         } -          to     } +  -}

Import Java.lang.reflect.method;import java.util.ArrayList;
public class Fanxing {
public static void Main (string[] args) {arraylist<string> list1 = new arraylist<string> (); ArrayList list = new ArrayList () List1.add ("HelloWorld");/* List1.add (20);//ToolTip error, indicating that eclipse is automatically compiled */class cs = List1.getclass (); Class no = List.getclass (), if (cs = = no) System.out.println (TRUE),/* * The answer is true to indicate that the compiled collection is generic to the generic * Java collection, to prevent input errors, only at compile time , bypassing the compilation is invalid * We can use the method of reflection to operate, bypassing the compilation */try {@SuppressWarnings ("unchecked") method M = Cs.getmethod ("Add", Object.class); M.invoke (List1, 20);//bypass the compilation and bypass the generic System.out.println (List1);} catch (Exception e) {e.printstacktrace ();}}
}

Java 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.