简体   繁体   English

获取通用类型或通用实例的类

[英]get class of generic type or generic instance

I have a method that 我有一种方法

  • has two type parameters T and S where S is superclass of T , 具有两个类型参数TS ,其中ST超类,
  • has an instance t of T as argument, 有一个T的实例t作为参数,
  • creates a new instance s of S , 创建S的新实例s
  • fills all fields of s with the content of t . t的内容填充s所有字段。

Here is the code: 这是代码:

public static <T extends S, S> S copyAs(T t, Class<S> sClass) {
    S s = sClass.newInstance();
    for (Field f : getAllFields(sClass)) {
        f.setAccessible(true);
        f.set(s, f.get(t));
    }
    return s;
}

private static Collection<Field> getAllFields(Class<?> cls) {
    Collection<Field> fields = new ArrayList<Field>();
    while (cls != Object.class)
    {
        fields.addAll(Arrays.asList(cls.getDeclaredFields()));
        cls = cls.getSuperclass();
    }
    return fields;
}

This works perfectly. 这很完美。

For convenience - in case I want to copy as the same class - I want a second method with just one argument. 为了方便起见-如果我想复制为同一类- 我想要第二个方法仅带有一个参数。 That method should internally just call copyAs(myInstance, MyClass.class) if myInstance is of type MyClass . 如果myInstance类型为MyClass copyAs(myInstance, MyClass.class)则该方法应在内部仅调用copyAs(myInstance, MyClass.class)

How do I do this? 我该怎么做呢? Is this possible at all? 这有可能吗?

I have tried two ways which both do not work: 我尝试了两种都不起作用的方法:

public static <T> T copy(T t) {
    return copyAs(t, T.class);
    // error: .class cannot be used on type parameter
}

and

public static <T> copy(T t) {
    return copyAs(t, t.getClass());
    // error: t.getClass() gives Class<? extends Object>, not Class<T>
}

T.class will never work -> you need to do some more reading about how java generics work. T.class将永远无法工作->您需要更多阅读有关Java泛型如何工作的内容。

This will do what you want: 这将做您想要的:

public static <T> T copy(T t) {
    Class<T> tc = (Class<T>) t.getClass();
    return copyAs(t, tc);
}

but it does raise a class cast warning -- there isn't really a way to not do that with the code that you want, feel free to suppress it. 但这确实会引发类强制转换警告-确实没有一种方法可以对所需的代码不执行此操作,可以随意对其进行抑制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM