[英]How can i create list of datatype of an existing object in java
Well the question says it all. 这个问题说明了一切。 Heres an Example of what i want
这是我想要的例子
String s = new String();
List<s.type> ls = new ArrayList<s.type>();
Something like that, or any elegant way to achieve this, please no multiple if conditions or condition logic, as there may be unlimited data types, i have used string here only as an example, it can be anything. 诸如此类的东西,或任何达到此目的的优雅方法,请不要在条件或条件逻辑中使用多个,因为可能存在无限的数据类型,我在这里仅以字符串为例,可以是任何东西。
If you want to get the runtime type of s and use it in a generic, this is impossible. 如果要获取s的运行时类型并在泛型中使用它,这是不可能的。 Generics in Java are used only in compile time for type-checking and type inference.
Java中的泛型仅在编译时用于类型检查和类型推断。 The generic's information is erased in the runtime, so the runtime can't tell the differense between
List<String>
and List<Integer>
. 泛型的信息在运行时被删除,因此运行时无法区分
List<String>
和List<Integer>
之间的区别。
If you just want to make a generic with the compile-time-known type for s, than it does not make sense, because you already know the type of s and you can write a class name for it. 如果只想使用s的编译时已知类型作为泛型,则没有意义,因为您已经知道s的类型并且可以为其编写类名。
If I understood you correctly, you want to know the class ( type ) of an instance ( object ) in runtime ( existing ), which has nothing to do with generics though, as Petr explained. 如果我对您的理解正确,那么您想知道运行时( 现有 )中实例( 对象 )的类( 类型 ),但是与泛型无关,正如Petr解释的那样。
public class Types {
public static void main(String[] args) {
String s = "";
Runtime r = Runtime.getRuntime();
Types t = new Types();
List<Class> types = new LinkedList<Class>();
types.add(Integer.class);
types.add(t.getClass());
types.add(r.getClass());
types.add(s.getClass());
for (Class type :types) {
System.out.println(type.getSimpleName());
}
}
}
which outputs: 输出:
Integer
Types
Runtime
String
However, such approach is rarely needed, so rethink is there a simpler solution to your problem. 但是,很少需要这种方法,因此请重新考虑是否有更简单的解决方案来解决您的问题。 If you still want to tackle it like this:
如果您仍然想像这样解决它:
EDIT: 编辑:
The other interpretation of your question leads to a dynamic generic list as answer: 对问题的另一种解释导致生成一个动态的通用列表作为答案:
public static <T> List<T> createListOfType() {
return new ArrayList<T>();
}
public static void main(String[] args) {
List<String> a = createListOfType();
List<Integer> b = createListOfType();
a.add("");
b.add(2);
a.add(2); // remove this line to compile
b.add(""); // remove this line to compile
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.