java吧 关注:1,232,906贴子:12,698,427
  • 0回复贴,共1

为什么找不到stu1这个对象呢,最后调用方法找不到,请教大佬

只看楼主收藏回复

public class refaclt {
public static void main(String[] args) throws Exception, Exception {
//Student stu=new Student();
//Class cla=stu.getClass();//通过对象的getClass()方法获取这个类的Class对象;
//Class cla=Student.class;//通过类的class属性获取这个类的class对象;
Class cla=Class.forName("ceshidemo.ceshidemo.Student");//通过Class 类的forname()方法获取这个类的class对象;
try {
Constructor co=cla.getConstructor(String.class,String.class,String.class);//获取指定的构造方法;
Student stu1=(Student)co.newInstance("张三","29","男");//新建student对象stu1;
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
Student stu2=(Student)cla.newInstance();
Field namefileld=cla.getField("name");
namefileld.set(stu2, "李四");
Method met1=cla.getMethod("setname", String.class);
met1.invoke( stu1,"王二麻");//stu1提示找不到;
}
}


IP属地:江苏1楼2018-03-08 11:20回复