[英]How to declare an object of a variable type
How do I declare an object of a variable type? 如何声明变量类型的对象? I know that I need to use generics, I've written this code but I'm not sure if it makes sense for what I want to do. 我知道我需要使用泛型,我已经编写了这段代码,但是不确定我想做什么。 I want to declare an object of a variable type, and pass either an int or a string as a parameter for the object constructor. 我想声明一个变量类型的对象,并传递一个int或一个字符串作为对象构造函数的参数。 Here is the code I wrote: 这是我写的代码:
CityOp(String CityT, Class<?>[] par) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException{
Class<?> co = Class.forName(CityT);
Op.getDeclaredConstructor(par);
}
Does the code make sense? 该代码有意义吗?
The question seemed a bit unclear to me. 我觉得这个问题有点不清楚。 If you're looking to pass in either a String
or an int
for the first parameter, and the second parameter must match the type of the first, then you can use a generic class to accomplish this, as follows: 如果您希望为第一个参数传递String
或int
,并且第二个参数必须与第一个参数的类型匹配,则可以使用通用类来完成此操作,如下所示:
public class CityOp<T> {
CityOp(T cityT, T[] par) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException{
// Constructor body here
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.