public Class<Example> getExampleByInstance(){
Example example = new Example();
// getClass是Object类里面的方法;《?》 是通配符
Class<?> clazz = example.getClass();
return (Class<Example>)clazz;
}
//获取所有的构造方法 / private public
public Constructor<?>[]getDeclaredConstructors()
//获取特定的构造方法 / private public
public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
//获取类的父类
public native Class<? super T> getSuperclass()
//获取类实现的接口
private Class<?>[]getInterfaces(boolean cloneArray)
//获取在类内定义的内部类或接口
public Class<?>[]getDeclaredClasses()
//获取所有的方法
public Method[]getDeclaredMethods() throws SecurityException
//根据方法名和参数获得特定的方法
public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
//获取类型的定义的所有属性
public Field[]getFields() throws SecurityException
// 根据属性命名获得特定的Field
public Field getField(String name)
Method常用的操作方法
//获得方法的放回类型
public Class<?> getReturnType()
//获得方法的传入参数类型
public Class<?>[]getParameterTypes()
//obj是实例对象,args是方法,反过来由Method控制对象的方法调用
public Objectinvoke(Object obj, Object... args)
public class Example {
private int value , count;
static public void main(String[] args) throws Exception{
Class<Example> clazz = Example.class;
//获取所有的属性,getField只能获取public的属性
Field[]fs = clazz.getDeclaredFields();
//根据名称获取指定 Field
Field value = clazz.getDeclaredField("value");
Example example = clazz.newInstance();
//使用反射机制可以打破封装性,导致了java对象的属性不安全
value.setAccessible(true); //setAccessible(true)让private的参数可赋值操作
//由Field反过去设置example的值
value.set(example,100);
System.out.println(example.value);
}
}