Java Notes: Reflection

Source: Internet
Author: User
Tags getmessage modifier

First, the basic knowledge

Class is a generic superclass that encapsulates the state of a class or interface runtime. Class is the center of reflection in Java, where you can find information about a class at run time.

class Solution {    publicstaticvoidthrows  classnotfoundexception {         = String. class; // Get through class literals        c = "Hello World". GetClass (); // get        through GetClass c = Class.forName ("String"); // get        through forname false, solution. class . getClassLoader ());}    }
View Code

Second, class reflection

ImportJava.lang.reflect.Modifier;Importjava.lang.reflect.TypeVariable;Importjava.util.List;classSolution { Public Static voidMain (string[] args) {Class C= List.class; intmodifier = 0;//modifier        if(C.isinterface ()) modifier= C.getmodifiers () &modifier.interfacemodifiers (); Elsemodifier = c.getmodifiers () &modifier.classmodifiers ();        System.out.println (modifier.tostring (Modifier)); Typevariable<?>[] types = C.gettypeparameters ();//Generic Parameters         for(typevariable t:types) System.out.println (T.gettypename ()); Class[] Interfaces= C.getinterfaces ();//implementing Interfaces         for(Class i:interfaces) System.out.println (i); }}
View Code


Third, field reflection

field to get information about the fields in the class.

Import Java.lang.reflect.Field; class Solution {    publicstaticvoid  main (string[] args) {        Class< string> C = String. class ;         = c.getfields ();          for (Field field:fields)            System.out.println (field);         // Public static final Java.util.Comparator Java.lang.String.CASE_INSENSITIVE_ORDER     }}
View Code

Iv. reflection of the method

Importjava.lang.reflect.*;classSolution {StaticString getmodifiers (executable exec) {intModifier =exec.getmodifiers (); if(execinstanceofMethod) modifier&=modifier.methodmodifiers (); Else if(execinstanceofConstructor) modifier&=modifier.constructormodifiers (); returnmodifier.tostring (Modifier); }    StaticString getparameters (executable exec) {parameter[] Parameters=exec.getparameters (); StringBuilder Str=NewStringBuilder ();  for(Parameter parameter:parameters) str.append (Parameter+ " "); returnstr.tostring (); }    StaticString getexceptions (executable exec) {StringBuilder str=NewStringBuilder (); Class[] CS=exec.getexceptiontypes ();  for(Class C:cs) str.append (c+ " "); returnstr.tostring (); }     Public Static voidMain (string[] args) {Class<Integer> C = Integer.class; Method[] Methods= C.getdeclaredmethods ();//do not include methods inherited from a superclass         for(Method method:methods) {System.out.println (Method.getname ());            System.out.println (GetModifiers (method));            System.out.println (GetParameters (method));        System.out.println (Getexceptions (method)); }    }}
View Code

V. Reflection object Creation

No parameter constructor.

 class   MyClass {MyClass () {System.out.pri    Ntln ( "Constructor called"  class   solution { public  static  void   main (string[] args) {Class  <MyClass> c = Myclass.class  ;  try   {MyClass o  = c.newinstance ();        System.out.println (o);  catch  (instantiationexception |        Illegalaccessexception exc) {exc.printstacktrace (); }    }}
View Code

With the parameter constructor.

ImportJava.lang.reflect.Constructor;classMyClass {MyClass (intI, String s) {System.out.println ("Constructor called");        System.out.println (i);    System.out.println (s); }}classSolution { Public Static voidMain (string[] args) {Class<MyClass> C = MyClass.class; Try{Constructor<MyClass> cons = C.getconstructor (int.class, String.class);//methods that can only call publicCons = C.getdeclaredconstructor (int.class, String.class);//all methods that can invoke this type of declarationMyClass o = cons.newinstance (0, "Hello World");        System.out.println (o); } Catch(Exception exc) {exc.printstacktrace (); }    }}
View Code

The reflection call method.

ImportJava.lang.reflect.Method;classMyClass { Public Static voidprint (String s) {System.out.println (s); }}classSolution { Public Static voidMain (string[] args) {Class<MyClass> C = MyClass.class; Try{MyClass o=c.newinstance (); Method Method= C.getmethod ("Print", String.class); Method.invoke (O,"Hello World"); } Catch(Exception exc) {exc.printstacktrace (); }    }}
View Code

Vi. Reflection Field Access

ImportJava.lang.reflect.Field;classMyClass { PublicString str = "Hello World";}classSolution { Public Static voidMain (string[] args) {Class<MyClass> C = MyClass.class; Try{MyClass o=c.newinstance (); Field name= C.getfield ("str"); String value=(String) name.get (o);            System.out.println (value); Name.set (O,"Hello World"); Value=(String) name.get (o);        System.out.println (value); } Catch(Exception exc) {exc.printstacktrace (); }    }}
View Code

Access to non-accessible fields, methods, and constructors.

ImportJava.lang.reflect.Field;classMyClass {PrivateString str = "Hello World";}classSolution { Public Static voidMain (string[] args) {Class<MyClass> C = MyClass.class; Try{MyClass o=c.newinstance (); Field Str= C.getdeclaredfield ("str"); if(!str.isaccessible ()) str.setaccessible (true); String value=(String) str.get (o);        System.out.println (value); } Catch(Exception exc) {System.out.println (Exc.getmessage ()); }    }}
View Code


Seven, array reflection

ImportJava.lang.reflect.Array;classSolution { Public Static voidMain (string[] args) {Try {            int[] ar = (int[]) Array.newinstance (int.class, 10);  for(inti = 0; I < 10; i++) array.set (AR, I, i);  for(inti = 0; I < 10; i++) System.out.println (Array.get (AR, i)); } Catch(Exception exc) {System.out.println (Exc.getmessage ()); }    }}
View Code

Gets the array dimension.

ImportJava.lang.reflect.Array;classSolution { Public Static voidMain (string[] args) {Try {            int[] arr = (int[]) Array.newinstance (int.class, 5, 5); Class C=Arr.getclass (); inti = 0;  while(C.isarray ()) {C=C.getcomponenttype (); I++;        } System.out.println (i); } Catch(Exception exc) {System.out.println (Exc.getmessage ()); }    }}
View Code

Expands an array.

ImportJava.lang.reflect.Array;Importjava.util.Arrays;classSolution {StaticObject Extend (object Oldarr) {intOldlength =array.getlength (Oldarr); intNewlength = Oldlength * 2; Class C=Oldarr.getclass (); Object NEWARR=array.newinstance (C.getcomponenttype (), newlength); System.arraycopy (Oldarr,0, NEWARR, 0, oldlength); returnNEWARR; }     Public Static voidMain (string[] args) {int[] arr =New int[5];  for(inti = 0; i < arr.length; i++) Arr[i]=i;        System.out.println (arrays.tostring (arr)); Arr= (int[]) extend (arr);  for(inti = 5; I < 10; i++) Arr[i]=i;    System.out.println (arrays.tostring (arr)); }}
View Code

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