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
上一篇: C#调用指定类中的私有方法或属性
下一篇: 设计模式---简单工厂模式(通俗易懂)
推荐阅读