简体   繁体   English

如何声明变量类型的对象

[英]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: 如果您希望为第一个参数传递Stringint ,并且第二个参数必须与第一个参数的类型匹配,则可以使用通用类来完成此操作,如下所示:

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.

相关问题 如何在 Java 中声明任何 class 类型的变量或 Object - How to declare a variable or Object of any class type in Java 如何声明接口类型的变量,然后将实现接口的 Class 的 object 分配给该变量,以及如何测试? - How to declare a variable of type Interface and then assign to the variable an object of a Class that implements the Interface, and how to test this? 如何在 avro 模式中声明类型为 Object 的实体 - how to declare an entity of type Object in avro schema 如何声明具有多个边界的类类型的对象 - How to declare object of type class with multiple bounds 如何通过字符串知道变量类型的声明类型 - How to declare a variable type knowing its type by a string 如何根据Java中输入变量的未知List类型声明变量? - How to declare a variable according to an unknown List type of the input variable in Java? 如何声明扩展参数化类型的类型变量? - How do I declare a type variable that extends a Parameterised type? 如何声明接口类型的变量说直接列表和赋值? - How to declare a variable of type Interface say List and assigning value directly? 如何在 Java 中声明某种类型的变量? - How do I declare a variable of certain type in Java? 如何在接口中声明方法签名以接受未知类型变量? - How to declare method signature in an interface to accept an unknown type variable?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM