欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java反射学习例子

程序员文章站 2022-03-09 21:36:45
...
package reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * 反射的学习
 * @author hjsjy
 *
 */
public class Test01 {
	public int a;
	private int b;
	private String cString;
	public String name;
	protected String dString;
	int d;
	public Test01() {
		System.out.println("构造方法");
	}
	private Test01(int a) {
		System.out.println("私有的构造方法"+a);
	}
	public Test01(int a,int b) {
		System.out.println("构造方法两个参数");
	}
	@Override
	public String toString() {
		return "Test01 [a=" + a + ", b=" + b + ", cString=" + cString + ", name=" + name + ", dString=" + dString
				+ ", d=" + d + "]";
	}
	public static void main(String[] args) throws Exception{
		Class<?> class1 = Class.forName("reflect.Test01");
		 Constructor<?>[] constructors = class1.getConstructors();
		 for(Constructor aConstructor :constructors) {
			 System.out.println(aConstructor);
		 }
		 System.out.println("---------------------------------------------------------------------------");
		 constructors = class1.getDeclaredConstructors();
		for(Constructor constructor: constructors) {
			System.out.println(constructor);
		}
		System.out.println("---------------------------------------------------------------------------");
		Constructor<?> declaredConstructor = class1.getDeclaredConstructor(int.class);
		System.out.println(declaredConstructor);
		declaredConstructor.setAccessible(true);
		Object newInstance = declaredConstructor.newInstance(1);
		System.out.println("---------------------------------------------------------------------------");
		Field[] fields = class1.getFields();
		for(Field f:fields) {
			System.out.println(f);
		}
		System.out.println("---------------------------------------------------------------------------");
		Field[] declaredFields = class1.getDeclaredFields();
		for(Field field :declaredFields) {
			System.out.println(field);
		}
		Field field = class1.getField("name");	
		System.out.println(field);
		Object newInstance2 = class1.getConstructor().newInstance();
		field.set(newInstance2, "hjsjy");
		Test01 test01=(Test01)newInstance2;
		System.out.println(test01.name);
		System.out.println("---------------------------------------------------------------------------");
		Field declaredField = class1.getDeclaredField("b");
		System.out.println(declaredField);
		declaredField.setAccessible(true);
		declaredField.set(newInstance2, 188);
		System.out.println(newInstance2);
		
	}
}


本文参考:https://blog.csdn.net/sinat_38259539/article/details/71799078?tdsourcetag=s_pcqq_aiomsg

相关标签: 反射