Research on the reflection mechanism of Java

Source: Internet
Author: User

Before listening at the same time said reflection is very powerful, read some related articles today to summarize the reflection.

Note: Reflection is mainly used in the development framework, that is, the production framework;
First, get the class object

class<?> C = class.forname ("classname"); Throw ClassNotFoundException


Second, get the implementation interface
class<?> inters[] = c.getinterfaces ();
for (int i=0;i<inters.length;i++) {
System.out.print (Inters[i].getname () + ""); GetName () method to get the interface name;
}

Third, obtain the parent class
Class<?> superclass = C.getsuperclass (); Get parent class
String name = Superclass.getname (); Get the parent class name

Iv. acquisition of structural methods
Constructor cons[] = c.getconstructors (); Get the public construction method
Constructor dcons[] = c.getdeclaredconstructors (); Get all construction methods
String modifier = modifier.tostring (Cons[i].getmodifiers ()); Get access rights
String name = Cons[i].getname (); Get constructor Method name
class<?> params[] = Cons[i].getparametertypes (); Get parameter type Object

v. Obtaining method
Method ms[] = C.getmethods (); Returns all public methods, including inheritance methods
Method dms[] = C.getdeclaredmethods (); Returns all methods of this class, not including inherited methods
class<?> RT = Ms[i].getreturntype ();
Class<?>params[] = Ms[i].getparametertypes ();
String name = Ms[i].getname ();
String modifier = modifier.tostring (Ms[i].getmodifiers ());
Class<?>ex[] = Ms[i].getexceptiontypes (); Get exception
String name = Ex[i].getname (); Get exception Name

vi. acquisition of Field
Field fs[] = C.getfields (); Get public properties, including inheritance properties
Field dfs[] = C.getdeclaredfields (); Get all the properties of this class
class<?> type = Fs[i].gettype (); Gets the type object of the property
String name = Fs[i].getname (); Get the name of the property
String modifier = modifier.tostring (Fs[i].getmodifiers ());


Vii. creating an object from reflection
(1)
class<?> C = class.forname ("person");
Person P = (person) c.newinstance ();
(2)
Constructor con = c1.getconstructor (Class....param);
Object obj = Con.newinstance (object obj); To create an instance from a constructor function

Viii. constructor Creating objects
Class C = class.forname ("person");
constructor<?> cons[] = c.getconstructors ();
Person P = (person) cons[0].newinstance ("Xiazdong", 15);
Note: If the calling constructor is private, c.setaccessible (true) is required;


Ix. calling a specific method
Method m = C1.getmethod ("FuncName", class<?>...c); FuncName represents the name of the calling method, and C represents the class object of the parameter
For example: Method m = C1.getmethod ("Fun", string.class,int.class); means call fun (string,int); function
Object obj = M.invoke (C1.newinstance (), "Xiazdong", 20); If there is a return value, the Invoke function returns;
Note: If you call a static method, you do not need to set the object;
Object obj = M.invoke (null, "Xiazdong");

Note: If there is an array in the parameter, such as public static void Main (String[]args);
The
Method m = C1.getmethod ("main", String[].class);
M.invoke (null, (Object) New string[]{"AA", "BB"});
M.invoke (null,new string[]{"AA", "BB"}); Will call main (string,string); function;

X. Calling a specific property

Field f = C1.getdeclaredfield ("name"); Returns the Name property
F.setaccessible (TRUE); Private properties Visible
String name = (string) f.get (Object obj); Returns the value of the Name property of the Obj object
F.set (Object obj,string N); Sets the Name property of the Obj object to the n value;


11. Manipulating Arrays
int tmp[] = {n/a};
class<?> C = Tmp.getclass (). Getcomponenttype ();
Array.getlength (TMP); The length of the TMP array
C.getname (); Get array type name
Array.get (Object obj,int index); Gets the value of the index index of the obj array
Array.set (Object obj,int index,value); Sets the value of the index of the obj array to value;
Object obj = array.newinstance (c,length); C is the type of the array, the length of the array, and obj is the object returned;
Example:

Import java.lang.reflect.*;p ublic class getmethoddemo01{public static void Main (String args[]) throws Exception{class <?> C1 = class.forname ("person"); Method m = C1.getmethod ("SayHello"); M.invoke (C1.newinstance ()); Method m2 = C1.getmethod ("SayHello2", String.class,int.class); String str = (string) M2.invoke (C1.newinstance (), "Xiazdong", 123); System.out.println (str); Field NameField = C1.getdeclaredfield ("name"); Field Agefield = C1.getdeclaredfield ("Age"); Namefield.setaccessible (true); Agefield.setaccessible (true); Person obj = (person) c1.newinstance (); Obj.setname ("Xzdong"); Obj.setage (12); System.out.println (Namefield.get (obj)); System.out.println (Agefield.get (obj)); Method setName = C1.getmethod ("SetName", String.class); Setname.invoke (obj, "changed"); Method getName = C1.getmethod ("GetName"); System.out.println (Getname.invoke (obj)); int tmp[] = {-N-a}; class<?> C3 = Tmp.getclass (). Getcomponenttype (); System.out.println (C3.getname ()); System.out.println ("First Number:" +array.get (tmp,0)); Array.set (tmp,0, 5); System.out.println ("First Number:" +array.get (tmp,0)), Object arr = array.newinstance (c3,5); System.arraycopy (Tmp,0,arr,0,array.getlength (TMP)); System.out.println (Array.get (arr,2)); System.out.println (Array.get (arr,3));}}

Import java.lang.reflect.*;interface china{public static final String NAME = "China";p ublic int-age = 60;public void sayhe Llo ();p ublic string SayHello2 (string Name,int age); Class Person implements china{private string Name;private int age;public string getName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} public void SayHello () {System.out.println (name+ "  " +age);} public string SayHello2 (String Name,int age) {return name+ "" +age;}}

11. Factory design Mode

1. The simplest factory design mode
Scene: There is a fruit interface, the Apple class and the Orange class have implemented the fruit interface, factory used to produce fruit;

Import Java.io.*;import java.util.*;interface fruit{public void Eat ();} Class Apple implements Fruit{public void Eat () {System.out.println ("Eat Apple");}} Class Orange implements Fruit{public void Eat () {System.out.println ("eating Oranges");}} Class Factory{public static Fruit getinstance (String name) throws Exception{fruit F = null;if ("Apple". Equals (name)) {f = ne W Apple ();} else if ("Orange". Equals (name)) {f = new orange ();} if (f!=null) {return F;} else return null;}} public class Factorydemo01{public static void Main (String args[]) throws exception{fruit F = factory.getinstance ("Apple") ; F.eat ();}}

2. Using reflection to achieve
One disadvantage of the above example is that the getinstance code in factory increases as the number of fruits increases, such as if a banana class is added, you need to add
if (Name.equals ("banana")) {...}
This is very inconvenient, so reflection is a good solution:

Import Java.io.*;import java.util.*;interface fruit{public void Eat ();} Class Apple implements Fruit{public void Eat () {System.out.println ("Eat Apple");}} Class Orange implements Fruit{public void Eat () {System.out.println ("eating Oranges");}} Class Factory{public static Fruit getinstance (String name) throws Exception{fruit F = nullfruit f = (Fruit) class.forname (NA Me). newinstance (); if (f!=null) {return F;} else return null;}} public class Factorydemo01{public static void Main (String args[]) throws exception{fruit F = factory.getinstance ("Apple") ; F.eat ();}}
3. Increased flexibility: Configuration files

However, one drawback is that if you have a package name such as the Apple class, you must add the package name + class name if you want to access this class. For example, at the top of the Apple class: Package org, it must be through Org. Apple can only access Apple classes. Therefore, through the properties file can solve this problem;

Import Java.io.*;import java.util.*;interface fruit{public void Eat ();} Class Apple implements Fruit{public void Eat () {System.out.println ("Eat Apple");}} Class Orange implements Fruit{public void Eat () {System.out.println ("eating Oranges");}} Class Factory{public static Fruit getinstance (String name) throws Exception{fruit F = nullfruit f = (Fruit) class.forname (NA Me). newinstance (); if (f!=null) {return F;} else return null;}        Private Factory () {}}public class factorydemo01{public static void Main (String args[]) throws exception{properties p = new P Roperties ();p. Load (New FileInputStream ("1.properties")); String str = p.getproperty ("Apple"); Fruit f = factory.getinstance (str); F.eat ();}}

1.propertiesCode:

Apple=apple
Orange=orange

Research on the reflection mechanism of Java

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.