Very good examples of Java reflection

Source: Internet
Author: User
Tags modifiers

1. The concept of Java reflection
Reflection meaning: You can get a running Java object.
2, the function of Java reflection
1) You can determine the class to which the run-time object belongs
2) You can determine the member variables and methods that run-time objects have
3) A method that can even be called to private by reflection
4) Generate dynamic agent
3. Classes that implement Java reflection
1) Class: It represents classes and interfaces in a running Java application
2) Field: Provides information about the properties of a class or interface, as well as its dynamic access rights
3) Constructor: Provides information about a single construction method of a class and access to it
4) Method: Provides information about one of the methods in a class or interface
Note: The class class is the most important feature class in Java reflection, and all information that gets the object (including: Method/property/constructor/access) needs it to implement
4. Steps to write the Java Reflector program:
1) You must first obtain the class object
For example:
Class C1 = Test.class;
Class C2 = class.forname ("Com.reflection.Test");
Class C3 = New Test (). GetClass ();
2) Then call the methods in the class object to get the structure of the properties/methods/constructors of a class
Note: If you want to be able to get a normal method/property/constructor in the class, you should focus on the following reflection classes
Field
Constructor
Method
Example: This program example shows you how to manipulate Class/field/constructor/method and other classes related to Java reflection
Package com.reflection;
Import Java.lang.reflect.Constructor;
Import Java.lang.reflect.Field;
Import java.lang.reflect.InvocationTargetException;
Import Java.lang.reflect.Method;
Import Java.lang.reflect.Modifier;
public class Testreflection {
Private String username;
private String password;
Private int[] age;
public void Setusername (String username) {
This.username = Username;
}
private void SetPassword (String password) {
This.password = password;
}
public static void test01 () throws ClassNotFoundException {
Class C1 = Testreflection.class;
Class C2 = class.forname ("com.reflection.TestReflection");
Gets the specified package name
String 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
int mod = C1.getmodifiers ();
String modifier = modifier.tostring (mod);
System.out.println ("modifier =" + modifier);
Gets the fully qualified name of the specified class
String className = C1.getname ();
System.out.println ("className =" + ClassName);
Gets the parent class of the specified class
Class Superclazz = C1.getsuperclass ();
String superclazzname = Superclazz.getname ();
System.out.println ("superclazzname =" + Superclazzname);
Get the implemented interface
Class[] interfaces = C1.getinterfaces ();
for (Class t:interfaces) {
System.out.println ("interfacesname =" + T.getname ());
}
Gets the member variable of the specified class
field[] fields = C1.getdeclaredfields ();
for (Field field:fields) {
Modifier = modifier.tostring (Field.getmodifiers ()); Get each
Access modifiers for fields
Class type = Field.gettype (); Gets the data type of the field that corresponds to the
Class object
String name = Field.getname (); Get field Name
if (Type.isarray ()) {//If the array type requires special handling
String Arrtype = Type.getcomponenttype (). GetName () +
"[]";
System.out.println ("" + modifier + "" + Arrtype + ""
+ name + ";");
} else {
System.out.println ("" + modifier + "" + Type + "" +
Name + ";");
}
}
Get the constructor method of a class
Constructor[] Constructors = c1.getdeclaredconstructors ();
for (Constructor constructor:constructors) {
String name = Constructor.getname (); Constructor Method Name
Modifier = modifier.tostring (Constructor.getmodifiers ()); Get access Modifiers
System.out.println ("" + modifier + "" + Name + "(");
class[] Paramtypes = Constructor.getparametertypes (); Get parameters in a constructor method
for (int i = 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 methods
Method[] 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 (int i = 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 void test02 () throws Instantiationexception,
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 first
Call Setaccessible (True)
Class C1 = Testreflection.class;
testreflection T1 = (testreflection) c1.newinstance (); Use reflection to create
Object of the building class
System.out.println ("username = =" + T1.username);
SYSTEM.OUT.PRINTLN ("Password = =" + T1.password);
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 modification");
SYSTEM.OUT.PRINTLN ("Password = =" + T1.password);
}
public static void Main (string[] args) throws ClassNotFoundException,
SecurityException, IllegalArgumentException, Instantiationexception,
Illegalaccessexception, Nosuchmethodexception, invocationtargetexception {
TEST01 ();
Test02 ();
}
}

Very good examples of Java reflection

Related Article

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.