基于泛型类型创建新对象

时间:2021-01-31 15:18:23

标签: java generics

是否可以基于泛型类型创建新对象。例如,我有几个自定义对象,我想调用一个泛型方法,该方法基于该泛型类型创建一个新对象。

public static void main(String[] args) {
    Customer cust = myObject("str");
    Vendor vend = myObject("str");
    ...
}

public static <T> T myObject(String str) {
    return new T(str);
}

我阅读了一些关于此的内容,我知道您不能那样做,但我就是无法让它发挥作用。例如,我尝试过 type.isInstance(str),但我的编辑说,我不应该使用它,它实际上不起作用。那么应该怎么做呢?

1 个答案:

答案 0 :(得分:3)

我不知道你为什么要创建不同类型的对象 通过通用的通用方法。 对我来说,它闻起来像一个糟糕的设计。

话虽如此,您可以通过以下方式实现:

public static <T> T myObject(Class<T> type, String str)
        throws InstantiationException, IllegalAccessException,IllegalArgumentException,
               InvocationTargetException, NoSuchMethodException, SecurityException
{
    return type.getDeclaredConstructor(String.class).newInstance(str);
}

你看,上面的方法接收一个 Class 参数, 以便它知道新创建的对象应该是哪个类。 该方法首先获取可以接受一个 String 参数的构造函数。 然后调用构造函数来实际创建对象。

你看,getDeclaredConstructornewInstance 方法 可能会抛出很多不同的异常。因此你需要 通过一些 try/catch 代码处理这些异常。 (为简洁起见,我在此处的代码中省略了这一点,并简单地添加了 throws 声明。) 这引发了有关此方法设计的一些危险信号。

上面的方法可以这样使用:

public static void main(String[] args) throws Exception
{
    Customer customer = myObject(Customer.class, "str");
    Vendor vendor = myObject(Vendor.class, "str");
}