Home > Java > Javagetting Started > Detailed introduction to java reflection mechanism

Detailed introduction to java reflection mechanism

王林
Release: 2019-11-25 14:48:36
forward
2565 people have browsed it

Detailed introduction to java reflection mechanism

This article is introduced in the Introduction to Java Programming column to introduce the reflection mechanism in Java in detail, hoping to help students who do not understand this mechanism.

java reflection

The mechanism is in the running state. For any class, all properties and methods (including private ones) of this class can be known; for any object , can call any of its methods and properties; this function of dynamically obtaining information and dynamically calling object methods is called Java's reflection mechanism.

Purpose:

Determine the class to which any object belongs at runtime.

Construct an object of any class at runtime.

Judge the member variables and methods of any class at runtime.

Call the method of any object at runtime.

Generate dynamic proxy.

Reflection related classes

Detailed introduction to java reflection mechanism

class class

obtained in Java program Class objects usually have the following three methods:

1. Use the forName(String clazzName) static method of the Class class. This method requires passing in a string parameter, the value of which is the fully qualified name of a class (the complete package name must be added).

2. Call the class attribute of a certain class to obtain the Class object corresponding to the class.

3. Call the getClass() method of an object. This method is a method in the java.lang.Object class.

Field

Field[] allFields = class2.getDeclaredFields();//获取class对象的所有属性
Field[] publicFields = class2.getFields();//获取class对象的public属性
Field ageField = class2.getDeclaredField("age");//获取class指定属性,可以获得私有属性
Field desField = class2.getField("des");//获取class指定的public属性
Copy after login

Method

Method[] methods = class2.getDeclaredMethods();//获取class对象的所有声明方法
Method[] allMethods = class2.getMethods();//获取class对象的所有public方法 包括父类的方法
Method method = class2.getMethod("info", String.class);//返回次Class对象对应类的、带指定形参列表的public方法
Method declaredMethod = class2.getDeclaredMethod("info", String.class);//返回次Class对象对应类的、
带指定形参列表的方法
Copy after login

Constructor

Constructor<?>[] allConstructors = class2.getDeclaredConstructors();//获取class对象的所有声明构造函数
Constructor<?>[] publicConstructors = class2.getConstructors();//获取class对象public构造函数
Constructor<?> constructor = class2.getDeclaredConstructor(String.class);//获取指定声明构造函数
Constructor publicConstructor = class2.getConstructor(String.class);//获取指定声明的public构造函数
Copy after login

Generating instance objects through reflection

1. Use the newInstance() method of the Class object to create an instance of the corresponding class of the Class object. This method requires that the corresponding class of the Class object has a default constructor, and when the newInstance() method is executed, the default constructor is actually used to create an instance of the class.

2. First use the Class object to obtain the specified Constructor object, and then call the newInstance() method of the Constructor object to create an instance of the corresponding class of the Class object. This way you can choose to use a specified constructor to create the instance.

Calling method

1. Obtain the specified method through the getMethods() method or getMethod() method of the Class object and return the Method array or object.

2. Call the Object invoke(Object obj, Object… args) method in the Method object. The first parameter corresponds to the instance object calling the method, and the second parameter corresponds to the parameters of the method.

Example code:

What is reflection?

package am;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import javax.activation.FileDataSource;
/**
 * 反射是什么:
 *    java中的反射:就是在类的加载过程中,发现类的属性和方法构造方法等信息。可以获得类的属性值,可以调用类的方法。
 *    
 * 
 * 反射获得类的对象。
 *
 */
public class Demo01 {
	public static void main(String[] args) throws Exception{
		// 通过反射,获取类的对象。
		Object obj = create("am.Foo");;
		Foo foo = (Foo)obj;
		System.out.println(foo.a);
		double dou = foo.show(12, "hello");
		System.out.println(dou);
		System.out.println("======================================");
		// 获得类的属性
		showField(obj);
		System.out.println("======================================");
		double a = (double)getFieldValue(obj, "b");
		System.out.println(a);
		System.out.println("========================================");
		// 通过反射调用方法。
		Object ob = getMethodValue(obj,"show",new Class[]{int.class,String.class},new Object[]{23,"abc"});
		double douValue = (double)ob;
		System.out.println(douValue);
	}
//通过反射调用方法,哪个对象,什么名称,参数类型,参数值
	public static Object getMethodValue(Object obj,String method,Class[] paramType,Object[] param)
	throws Exception{
		Class cla = obj.getClass();
		Method me = cla.getDeclaredMethod(method, paramType);
		Object o = me.invoke(obj, param);
		return o;
	}
	// 获取类的属性值:
	public static Object getFieldValue(Object obj,String name)throws Exception{
		Class cla = obj.getClass();// 获取字节码对象。
		Field field = cla.getDeclaredField(name);// 通过属性的名称。获取当前属性。
		Object result = field.get(obj);
		return result;
	}
	// 通过反射,可以获得类的属性信息以及方法信息。
	public static void showField(Object obj){
		// java中对属性类。 Field   方法类:Method
		Class cla = obj.getClass();
		System.out.println("获取类名:"+cla.getName());
		System.out.println("======================================");
		// 获取类的属性:
		Field[] fields = cla.getDeclaredFields();// 获取公开的属性。
		for(Field field : fields){
			System.out.println("获取类的属性类型"+field.getType());
			System.out.println("获取类的属性名称:"+field.getName());
		}
		System.out.println("======================================");
		// 获取类的方法。
		Method[] methods = cla.getDeclaredMethods();
		for(Method method : methods){
			System.out.println("获取方法的返回值类型:"+method.getReturnType());
			System.out.println("获取方法名称:"+method.getName());
			System.out.println("获取方法的参数类型。"+Arrays.toString(method.getParameterTypes()));
		}
		System.out.println("=======================================");
		// 获取类的构造方法:
		Constructor[] cons = cla.getDeclaredConstructors();
		for(Constructor con : cons){
			System.out.println("构造方法的名字:"+con.getName());
			System.out.println("构造方法参数类型:"+Arrays.toString(con.getParameterTypes()));
		}	
	}
	// 如何反射类的实例。
	public static Object create(String name) throws Exception{
		// 反射的方法。Class.forName();
		Class cla = Class.forName(name);
		// 如何获得Object类型对象。
		Object obj = cla.newInstance();
		return obj;
	}
}
// 模拟类。
class Foo{
	int a = 10;
	double b = 20;
	public double show(int p,String str){
		System.out.println("调用方法传入的值是:"+str);
		return a+b+p;
	}
	public Foo(){
	}
	public Foo(int a,int b){
	}
}
Copy after login

More related learning video recommendations: java video tutorial

The above is the detailed content of Detailed introduction to java reflection mechanism. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template