[英]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.