![](/img/trans.png)
[英]Instance method not called when declaring a Class-type instance variable and call an instance method in Esper
[英]How to pass a .class-type parameter into a method
PersonenGenerator{
Set<Person> personSet = new HashSet<>();
public void printPersonTypeSet(Class clazz){ //pass a class that inherits from the class Person as a parameter
for(Person instance : personSet){
if (instance instanceof clazz) System.out.println(instance);
} // check if instance of Class Person are stored in personSet. If so, print said instance
}
public class Student extends Person{
...
}
public class Employee extends Person{
...
}
public class Main {
public static void main(String[] args) {
PersonenGenerator pg = new PersonenGenerator();
pg.Student s1 = new Student(...);
pg.personSet.add(s1);
pg.Employee e1 = new Employee(...);
pg.personSet.add(e1);
printPersonTypeSet(Employee) //pass Employee as parameter SOMEHOW
}
}
預期行為(輸出):
員工{value1,value2,value3}
由於某些原因,我的編譯器不喜歡if語句。 我特別稱呼clazz
。
實際行為(編譯器錯誤):
未知類別:“ clazz”
我的問題是我打算將clazz
用作Person
實例的變量,而Person
是各種子類的超類。
如何保持預期的功能並滿足我的編譯器要求? 第一次這樣做。
編輯:我覺得我被誤解了。 我想通過一個類作為檢查條件的參數。 我評論了代碼以澄清這一點。
如果為此將參數傳遞為Class
類型是胡說八道,那就這么說。 這是一個主意,因為我不知道如何將類作為參數傳遞。
您需要clazz.isAssignableFrom(instance.getClass())
。 這將返回true
,如果instance
有型clazz
或類型的子類型clazz
。
編輯:這是一個更完整的示例。 您有一個Person
類和一些子類:
class Person {
String name;
Person(String n) { name = n; }
public String toString() { return name; }
}
class GoodPerson extends Person {
GoodPerson(String n) {
super(n);
}
}
class BadPerson extends Person {
BadPerson(String n) {
super(n);
}
}
然后,將您的代碼與我建議的編輯一起使用:
public void printPersonTypeSet(Class<?> clazz) {
for (Person instance : personSet)
if (clazz.isAssignableFrom(instance.getClass()))
System.out.println(instance);
}
如果personSet
初始化為:
Set<Person> personSet = new HashSet<Person>();
personSet.add(new GoodPerson("Good1"));
personSet.add(new GoodPerson("Good2"));
personSet.add(new BadPerson("Bad1"));
然后您可以使用printPersonTypeSet(GoodPerson.class)
查找GoodPerson
的實例。 (請注意,這也會找到GoodPerson
子類。)
在您的示例中, clazz
是Class
的實例,而這可能並不是您想要在方法中提供的參數。 因此,您要問編譯器instance
是否是clazz
的實例,而不能因為clazz
不是類而是實例而不能成為clazz
的實例。
最好的方法是使用isInstance(Class)
方法。 根據Java文檔,此方法動態等效於Java語言instanceof運算符。
public void printPersonTypeSet(Class clazz){
Set<Person> personSet = ImmutableSet.of(new Person());
for(Person instance : personSet){
if (clazz.isInstance(instance.getClass())) System.out.println(instance);
}
}
public static void main(String[] args) {
new Scratch().printPersonTypeSet(Person.class);
}
從Java文檔:
確定指定的{@code對象}是否與此{@code類}表示的對象賦值兼容。 此方法動態等效於Java語言{@code instanceof}運算符。 如果指定的{@code Object}參數為非null,並且可以強制轉換為此{@code Class}對象表示的引用類型,而無需引發{@code ClassCastException。},則該方法返回{@code true}。它返回{ @code false},否則。
方法簽名
public native boolean isInstance(Object obj)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.