@Test
public void test1(){//获取对应运行时类的属性
Class cl=Kobeman.class;
Field[] fields=cl.getFields();//只能获取public属性,包括父类
for(int i=0;i<fields.length;i++){
// System.out.println(fields[i]);
}
Field[] fields1=cl.getDeclaredFields();//获取所有属性
for(Field field:fields1){
System.out.println(field.getName());//获取属性名
int i=field.getModifiers();//获取权限修饰符
//System.out.println(i);
String string= Modifier.toString(i);//
System.out.println(""+string);
Class type= field.getType();
System.out.println(type.getName()+"");//获取属性类型
}
}
@Test
public void test2(){
Class c=Kobeman.class;
Method[] methods=c.getMethods();//获取运行时类及其父类的Public方法
for(Method method:methods){
System.out.println(method);
}
Method[] methods_1=c.getDeclaredMethods();//获取运行时类所有方法
for(Method method:methods_1){
System.out.println(method);
System.out.println(method.getName());//方法名
String string=Modifier.toString(method.getModifiers());
System.out.println(string+"");//获取权限修饰符
Class returnType= method.getReturnType();
System.out.println(returnType.getName()+"");//返回值类型
Class[] parameters=method.getParameterTypes();//形参列表
for(int i=0;i<parameters.length;i++){
System.out.print(parameters[i].getName()+"arg_"+i+" ");
}
Class[] exception=method.getExceptionTypes();//获取异常类型
for(int i=0;i<exception.length;i++){
System.out.print(exception[i].getName()+"exception_"+i+" ");
}
}
}
//调用指定的构造器,调用指定的方法,调用指定的属性
@Test
public void test3() throws Exception{
Class cl1=Kobeman.class;
Field name=cl1.getField("Name");//获取 指定 属性
Kobeman kk=(Kobeman) cl1.newInstance();//创建运行时类的对象
System.out.println(kk);
name.set(kk,"Kobe");
System.out.println(kk);
Field age=cl1.getDeclaredField("age");
age.setAccessible(true);//可访问private属性,可被操作
age.set(kk,"24");
System.out.println(kk);
///////////////////////////////////////////////////
Method mm=cl1.getMethod("show");//获取 指定 方法 getMethod() 调用public的方法
Object returnVal=mm.invoke(kk);
System.out.println(returnVal);
///////////////////////////////////////////////////
Method mm_1=cl1.getMethod("toString");//获取 指定 方法
Object returnVal_1=mm_1.invoke(kk);//invoke 调用指定的方法
System.out.println(returnVal_1);
///////////////////////////////////////////////////
Method mm_2=cl1.getMethod("slam");//静态方法的调用
mm_2.invoke(Kobeman.class);
///////////////////////////////////////////////////
Method mm_3=cl1.getDeclaredMethod("display", String.class, Integer.class);//获取运行时类中非public的方法
mm_3.setAccessible(true);
Object val=mm_3.invoke(kk,"火星","24");
System.out.println(val);
///////////////////////////////////////////////////
String className="SnowCH20190110.Kobeman";
Class cl=Class.forName(className);
Constructor constructor=cl.getDeclaredConstructor(String.class,Integer.class);//调用指定的构造器
Kobeman kk_24=(Kobeman) constructor.newInstance("宋小艾","23");
System.out.println(kk_24);
}
}
JAVA#反射总结二 札记
猜你喜欢
转载自blog.csdn.net/Iverson941112/article/details/86428871
今日推荐
周排行