java中强制类型转换
publicstaticvoidmain(String[]args){try{Classc=Student.class;//获取无参数的构造函数Constructorco...
public static void main(String[] args) {
try {
Class c=Student.class;
//获取无参数的构造函数
Constructor constructor=c.getConstructor(new Class[]{});
//通过构造函数的反射来创建对象
Student stu=(Student)constructor.newInstance(new Object[]{});
stu.setAge(30);
System.out.println(stu.getAge());
System.out.println("===================================");
Constructor constructor1=c.getConstructor(new Class[]{String.class,int.class});
/*
Student stu1=(Student)constructor1.newInstance(new Object[]{"zhangsan",30});
System.out.println(stu1.getAge()+","stu1.getName());
*/
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
/**/的里面一直报错,是为什么啊,一直是30那个错,好像不能把int类型转成object类型
可是老师讲的是可以。
这是Student类
class Student{
private int age;
private String name;
public Student(){}
public Student(int age, String name) {
super();
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
这是两条错误信息:
No suggestions available
Rename in file 展开
try {
Class c=Student.class;
//获取无参数的构造函数
Constructor constructor=c.getConstructor(new Class[]{});
//通过构造函数的反射来创建对象
Student stu=(Student)constructor.newInstance(new Object[]{});
stu.setAge(30);
System.out.println(stu.getAge());
System.out.println("===================================");
Constructor constructor1=c.getConstructor(new Class[]{String.class,int.class});
/*
Student stu1=(Student)constructor1.newInstance(new Object[]{"zhangsan",30});
System.out.println(stu1.getAge()+","stu1.getName());
*/
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
/**/的里面一直报错,是为什么啊,一直是30那个错,好像不能把int类型转成object类型
可是老师讲的是可以。
这是Student类
class Student{
private int age;
private String name;
public Student(){}
public Student(int age, String name) {
super();
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
这是两条错误信息:
No suggestions available
Rename in file 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询