問題描述
創建一個類對象列表以將它們與另一個類對象進行比較 (creating a list of class objects to compare them with another class object)
首先,對不起,這個問題可能已經回答了,但我的搜索並沒有真正告訴我任何事情,而且我也不知道我在搜索什麼。
基本上,我需要創建一個類對象的List
(只存儲類/不存儲初始化的對象 ‑ 真的不知道如何解釋)並將它們與另一個類對象進行比較(ala instanceof </代碼>)。但我不知道該怎麼做。
一個例子是:
我想這樣做:
if(something1 instanceof something2)
帶有一個List
的“something1's”,以便能夠像這樣遍歷它:
for(int i= 0 ; i <= list.size; i++)
{
if (list.get(i) instanceof something2)
doSomething();
}
參考解法
方法 1:
You can compare classes using equals()
method, this method will check if the class is exactly the same.
So you first put classes in a list (assuming you have classes Foo
and Bar
and a list is List<Class>
):
list.add(Foo.class);
And then you iterate over it and do comparison like this:
if (list.get(i).equals(Bar.class))
doSomething();
方法 2:
Class
class provides API to do instance of
like check:
Class numClass = Number.class;
List<Class> classes = Arrays.asList(Integer.class);
...
if (numClass.isAssignableFrom(classes.get(i))) {
doSomething();
}
方法 3:
Using generic lists and class Class:
List<Class> classes = new ArrayList<Class>();
classes.add(Integer.class);
classes.add(String.class);
classes.add(MyClass.class);
//...
for (Class myClass : classes) {
if (myClass.equals(MyOtherClass.class)) {
doSomething();
}
}
方法 4:
List of classes can be declared as List<Class> list
, e.g.
List<Class> classes = Arrays.asList(String.class, Number.class);
Class testedClass = Integer.class;
If you want to test the exact classes equality use equals
.
for (Class clazz : list) {
if (clazz.equals(testedClass)) {
doSomething();
}
}
Or even shorter
if (list.contains(testedClass)) {
doSomething();
}
But if you need an analogue of instanceof
then use isAssignableFrom
for (Class clazz : list) {
if (clazz.isAssignableFrom(testedClass)) {
doSomething();
}
}
isAssignableFrom
means that clazz
and testedClass
are in the same hierarchy and testedClass
extends or equals to class
(by Alex Epvp、Krzysztof Krasoń、hoaz、marcellorvalle、Evgeny)
參考文件