如何创建未知类型的实例?

如何创建未知类型的实例?

问题描述:

我有几个函数需要精确的参数类型(又名 T ):

I have a couple of functions which requires exact argument type (aka T):

private <T> void doWork1(T _obj) {...}
private <T> void doWork2(T _obj) {...}
private <T> void doWork3(T _obj) {...}

我像这样使用它们并且工作正常:

I use them like this and it works fine:

public void parse(int id) {
    switch (id) {
        case 1: {
            Integer obj = new Integer(1);
            doWork1(obj);
            doWork2(obj);
            doWork3(obj);
            break;
        }
        case 2: {
            Double obj = new Double(2);
            doWork1(obj);
            doWork2(obj);
            doWork3(obj);
            break;
        }
        case 3: {
            CustomClass obj = new CustomClass();
            doWork1(obj);
            doWork2(obj);
            doWork3(obj);
            break;
        }
    }
}

但我想知道它是不是可以使代码更简洁,即

But I was wondering if it's possible to make the code more concise i.e.

public void parse(int id) {
    UnknownType obj;
    switch (id) {
        case 1: {
            obj = new Integer(1);
            break;
        }
        case 2: {
            obj = new Double(2);
            break;
        }
        case 3: {
            obj = new CustomClass();
            break;
        }
    }
    doWork1(obj);
    doWork2(obj);
    doWork3(obj);
}

如果是这样,我应该放什么代替 UnknownType

编辑:

1)我使用整数和 Double 作为简化示例。在我的实际代码中,我使用自定义类。
2)我需要知道我的 doWork 函数中的确切类型(类),所以我不能使用对象

提前致谢

If so what should I put instead of UnknownType?

1) I used Integer and Double as a simplified example. In my actual code I use custom classes.
2) I need to know exact type (class) in my doWork functions so I can't use Object
Thanks in advance

您可以使用 Number Object ,它们都是 Integer 和 Double 。

You can use Number or Object, which are both common supertypes of Integer and Double.

但是,泛型是不必要的:

However, the generics are unnecessary:

private <T> void doWork1(T _obj) {...}

private void doWork1(Object _obj) {...}

$ b $擦除后b

after erasure.

为输入参数设置类型变量的唯一要点是:

The only point of having a type variable for an input parameter is if:


  • 您需要指明另一个输入参数的泛型需要相关,例如您正在传递 T _obj List< T> _list

请注意, T _obj1 不需要通用类型和 T _obj2 ,但是 - 退化到 T 的上限(例如 Object );

Note that you don't need a generic type for T _obj1 and T _obj2, though - that degenerates to the upper bound of T (e.g. Object);

如果您需要它与退货类型相关:

If you need it to be related to the return type:

<T> T doWork1(T _obj) { ... }


你在这里不需要任何一个案例,所以只需删除不必要的并发症。

You don't need either case here, so just remove the unnecessary complication.