反射的学习
package xzx.getandset;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
public class GetAndSetDemo{
public static void main(String args[]){
Class<?> cls = null;
Person per = null;
try{
cls = Class.forName("xzx.getandset.Person") ;
}catch(ClassNotFoundException e){
e.printStackTrace();
}
System.out.println(cls);
try{
per = (Person)cls.newInstance();
}catch(Exception e){
e.printStackTrace();
}
System.out.println(per);
Constructor<?> cons[] = cls.getConstructors();
try{
per = (Person)cons[1].newInstance("xzx",19);
}catch(SecurityException e){
e.printStackTrace();
}catch(InstantiationException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
System.out.println(per);
System.out.println(cons[0]);
System.out.println(cons[1]);
Class<?> p[] = cons[1].getParameterTypes();
Class<?> o = cls.getSuperclass();
System.out.println(o.getName());
//打印方法名称
System.out.println(Modifier.toString(cons[1].getModifiers()));
}
};
class Person{
private String name;
private int age;
public Person(){
setName("默认的");
setAge(99);
}
public Person(String name,int age){
setName(name);
setAge(age);
}
public void setName(String name){
this.name = name;
}
public void setAge(int age){
this.age = age;
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
public String toString(){
return "姓名:" + this.getName() + " ---- 年龄:" + this.getAge();
}
};希望路过的大神们赐教
本文通过一个具体的Java程序示例,介绍了如何使用反射机制创建对象并调用构造方法。展示了如何获取类信息、实例化对象及调用带有参数的构造器。
5596

被折叠的 条评论
为什么被折叠?



