问题描述
- 在java反射中如何将c.newInstance()转为具体的类 而不是object?
-
package test.action;import test.entity.City;
public class Test {
public static void main(String[] args) {
City c=new City("111","江苏","22");
show(City.class);
}
public static void show(Class c1){
try {
Class c =Class.forName(c1.getName());
c.getConstructors();
try {
City o=(City) c.newInstance();
//这里如果不采用上述强转,该怎么得到City对象呢?} catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
}
解决方案
你要是直接用City类的话就可以不需要强转的,而如果是单纯用Class实例化的话则必须要强转
City city = City.class.newInstance();
解决方案二:
还有一种方法,也是不需要强转的:
package test.action;
import test.entity.City;
public class Test {
public static void main(String[] args) {
City c=new City("111","江苏","22");
show(City.class);
}
public static void show(Class c1){
try {
Class tempClass = Class.forName(c1.getName()); //添加tempClass临时变量之后就不需要强转了
Class<City> c = tempClass; // 通过泛型的类型参数
c.getConstructors();
try {
City o= c.newInstance(); // 不需要强转
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
解决方案三:
public static void show(Class<City> c1){ //加入泛型
//Class c =Class.forName(c1.getName()); //这行应该可以去掉直接用c1
//c1.getConstructors();
try {
City o=c1.newInstance();
}catch (Exception e) {
e.printStackTrace();
}
}
但加了泛型这参数就没多大意义,不如直接写成这样
public static void show(){ //加入泛型
try {
City o=City.class.newInstance();
}catch (Exception e) {
e.printStackTrace();
}
}
时间: 2024-11-02 02:57:30