import java.lang.reflect.*;
class MyReflection
{
public static void main(String[] args) throws Exception //20 98 164 168 680
{
Class clazz=Person.class;
Object obj=(Person)clazz.newInstance( );
System.out.println(obj);
//Constructor cons=clazz.getConstructor();错误 只有getConstructors()
Constructor cons1=clazz.getConstructor(String.class,int.class);
Object obj1=(Person)cons1.newInstance("张三",33 );
Method method=clazz.getMethod("setName",String.class);
method.invoke(obj,"java7");
System.out.println(obj);
//method.invoke(obj1,"王五");
Field field=clazz.getDeclaredField("age");
field.setAccessible(true);
//Object objv=field.get(obj);
//field.set(objv,"朱六"); 这两个编译不通过 该怎么改
}
}
class Person
{
private int age=0;
private String name="";
public Person(){
name="java";
age=16;
}
public Person(String name,int age){
this.name=name;
this.age=age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public void setName(String str){
name=str;
}
public void setAge(int nage){
age=nage;
}
public String toString(){
return "name:"+name+"---"+"age:"+age;
}
} |
|