English 中文(简体)
我如何以某种方法获得收集要素类型?
原标题:How do I get the element type of a collection passed in a method?

附录一有某种方法接受<代码>List<?>。

public void method(List<?> list) {
    // some logic
}

我怎样才能在运行时间获得这一要素类型? 是否可能?

I found these suggestions (here on SO):

  1. ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0] (doesn t work, List is an interface and doesn t have a superclass)
// ChatGPT s work

public class App {
    public static void main(String[] args) {
        List<String> stringList = new ArrayList<>();
        List<Integer> integerList = new ArrayList<>();

        Type stringType = getListElementType(stringList);
        Type integerType = getListElementType(integerList);

        System.out.println("String List Element Type: " + stringType.getTypeName());
        System.out.println("Integer List Element Type: " + integerType.getTypeName());
    }

    private static Type getListElementType(List<?> list) {
        Type genericType = list.getClass().getGenericSuperclass();

        if (genericType instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericType;
            return parameterizedType.getActualTypeArguments()[0];
        }

        throw new IllegalArgumentException("Unable to determine list element type.");
    }
}

青春期产出:

String List Element Type: E
Integer List Element Type: E
  1. Storing a corresponding class as a field during creation of a generic class instance (doesn t work, List is read-only, and it can t have any instance fields anyway since it s an interface)
/*
 from jqno s answer to "How can I learn actual type argument of an generic class?"
 Henning in his answer to "Get generic type of class at runtime" suggested a similar trick
*/

class ParameterizedClass<T> {
    private Class<T> type;

    /** Factory method */
    public static <T> ParameterizedClass<T> of(Class<T> type) {
        return new ParameterizedClass<T>(type);
    }

    /** Private constructor; use the factory method instead */
    private ParameterizedClass(Class<T> type) {
        this.type = type;
    }

    // Do something useful with type
}
  1. The TypeTools library. I still need some supertype

类型Resolver类别提供了以下几种方法:

Type reify(Type type, Class<S> context)

采用从具体情况中可变信息的类型,回归类型完全重新调整。

<编码> 类型重新编号(Type generalType)

Returns a fully reified genericType using information from the generic declaration.

Class<?>>。

解决使用亚甲苯类变异信息的类型方面的原始论点。

Class<?>solRawArgument (Class<T>打字、分类和提字;S> subType)

解决使用亚甲苯的类型变异信息的类型方面的原始论点。

<编码> 类型决定

采用亚类变异信息的类型确定通用类型。

Class<?>solRawClass (Type general) 类型、类别和类别; 和; 次级类型:

普通类原产阶级 使用亚丁那类变量信息的类型。

问题回答

我怎样才能在运行时间获得这一要素类型? 是否可能?

No.

通用课程是汇编者的想象力。 它们是将使用类型的地方连接起来的工具,以便告诉汇编者: 这些类型的工作需要相同——为其工作注入活力。 如果你能够证明类型不上线,就会产生汇编错误。 www.un.org/Depts/DGACM/index_french.htm

剩下的唯一一件事是: in signature,但什么仍然是exact,你在源代码中写过。 不是实际类型。 换言之,考虑到:

public class MyExample<E> {
  public void addAll(Collection<E> element) {
    List<String> x = new ArrayList<String>();
    check(x);
  }

  public void check(Object o) {
    // ...
  }
}

<代码>x变量的通用名称为completely go。 <<>0>0> > > > 代码>check 能够收回其编号为<编码>St。 <代码>new ArrayList<String>>和new ArrayList<Integer>100%相同的——它并非只有APIC获得这一信息,而是更为严格的: 页: 1

http://www.un.org/Depts/DGACM/index_french.htm 所有方法——但从字面上看,请查阅<代码>。 E 。 无用。

因此,要重复:No. 是不可能的

什么类型工具确实存在,是滥用签字的存续,并结合认识到:

List<String> list = new ArrayList<String>();

通用部分刚刚完全消除,包括:

List<String> list = new ArrayList<String>() {};

不是。 这是因为有许多黑客:

  • ArrayList is not final. had it been, the above wouldn t have compiled.
  • The above is almost the same as the first snippet, but in meaning, completely different: That is declaring an entirely new class with an anonymous name, defined as extends ArrayList<String>, and with class body {} (as in, it does not add anything). What a class extends is signature and thus not erased, and thus, at runtime you can recover this stuff.

然而,由于它引进了一整套热点,而通用体是字面的,因此这并不好。 例如,如果我写:

public <E> createList() {
  return new ArrayList<E>() {}
}

这一工程完全是罚款的,可以称为:List<String> myList = LevelThatIsIn.<String>createList();,然而,唯一可追溯到这种类型的超级大豆/型托醇/其他图书馆的运行时间是。 E ——字面上。 E. Not String——这是不可能做到的,因为这完全消失了。

因此,你的超型号是手法和长串点。 更一般地说,这样做并不是一种好的想法,而不是为了携带这种信息而设计的那种,而只是表面的。 一种没有意义的类型是,你要写的是:<条码>,SuperType Token<List<String>> my Token RepresentingListOfStrings = 新的超级大豆-Token<List<String >{}/code>。

This weird hackery can be useful if you have a need to convey things that generics can capture (i.e. not just a type, but any generics on that, as well. a Map<String, List<? extends Number>> for example - not just Map, no, that whole thing - java.lang.Class cannot represent that). Not to write a method that can ascertain what the generics are.

没有工作。 鉴于:

public void method(List<?> list) {
    // some logic
}

The answer is no. A whole heap of blogposts and articles beat around the bush and suggests ways to get to yes, but they re all incorrect. There is no way to do it. Period. super type tokens / typetools is something quite different. There is no way to use such tools to make that a yes .

职业经历 我失踪了,或者说不可行,但又是如何?

public static void main(String[] args) {
    
    List<String> stringList = new ArrayList<>();
    stringList.add("");
    List<Integer> integerList = new ArrayList<>();
    integerList.add(1);
    
    Main m = new Main ();
    m.method(stringList);
    
    m.method(integerList);
    
}

public void method(List<?> list) {
   
    Object o = list.get(0);
    System.out.println(o.getClass());
}

output

class java.lang.String
class java.lang.Integer




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签