java常用反射方法以及用法总结
package reflect;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface D{
}
interface C{
public int c();
}
@D
class B{
private int b;
public void b() {
System.out.println("b");
}
public void b2(int a) {
System.out.println("b2"+a);
}
}
public class A extends B implements C{
public A() {
}
public A(int a) {
}
@Override
public int c() {
// TODO Auto-generated method stub
return 0;
}
private int a;
public int a2;
public static void main(String[] args) throws NoSuchMethodException,
SecurityException, InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException, NoSuchFieldException {
//获取class对象 1.Class.forName(),2.类名.class,3.对象.getClass()
Class<?> a=A.class;
String name=a.getName();//获取类名
A obj=(A) a.newInstance();//反射创建对象
{
Method m=a.getMethod("b",null);//获取方法
Method m2=a.getMethod("b2",int.class);//获取方法
String mname=m.getName();//获取方法名
System.out.println(mname);
mname=m2.getName();//获取方法名
System.out.println(mname);
m.invoke(obj,null);//反射执行方法
m2.invoke(obj,1);
m.getAnnotation(D.class);//获取上面方法的注解
m.getAnnotations();//获取方法上的所有注解(数组)
m.getReturnType();//获取方法的返回值类型
Class<?>[] mcs=m2.getParameterTypes();//获取该方法所有参数类型(数组)
Method[] ms=a.getDeclaredMethods();//获取类的所有方法数组
}
{
Field af=a.getField("a2");//获取共有属性
Field pf=a.getDeclaredField("a");//获取私有属性
Field afs[]=a.getDeclaredFields();//获取所有属性(数组)
af.set(obj,1);//给对象属性赋值
pf.setAccessible(true);//设置可以访问私有属性
pf.set(obj,2);//给对象的私有属性赋值
int val=(int) pf.get(obj);//获取对象中属性的值
af.getType();//获取属性类型
af.getAnnotation(D.class);//获取属性上的注解
af.getAnnotations();//获取属性上的所有注解
}
Class<?> sc=a.getSuperclass();//获取父类class对象
a.getAnnotation(D.class);//获取类上的注解
a.getClasses();
//返回一个包含某些 Class 对象的数组,这些对象表示属于此 Class
//对象所表示的类的成员的所有公共类和接口。
a.getClassLoader();//获取该类的类加载器
a.getConstructor(int.class);
//返回一个 Constructor 对象,它反映此 Class 对象所表示的类的指定公共构造方法
a.getConstructors();
//返回一个包含某些 Constructor 对象的数组,
//这些对象反映此 Class 对象所表示的类的所有公共构造方法。
a.getDeclaredConstructor(int.class);
// 返回一个 Constructor 对象,该对象反映此 Class 对象所表示的类或接口的指定构造方法。
a.isInstance(obj);//判定指定的 Object 是否与此 Class 所表示的对象赋值兼容
a.isPrimitive();//判定指定的 Class 对象是否表示一个基本类型
}
}