简体   繁体   English

如何将.class类型参数传递给方法

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

EXPECTED BEHAVIOUR (Output): 预期行为(输出):

Employee{value1, value2, value3} 员工{value1,value2,value3}

My Compiler does not like the if-statement for some reason. 由于某些原因,我的编译器不喜欢if语句。 Specifically where i call clazz . 我特别称呼clazz

ACTUAL BEHAVIOR (Compiler Error) : 实际行为(编译器错误):

Unknown Class:'clazz' 未知类别:“ clazz”

My problem is that I intend to use clazz as a variable for instances of Person , while Person is the superclass for various subclasses. 我的问题是我打算将clazz用作Person实例的变量,而Person是各种子类的超类。

How do I keep the intended functionality and satisfy my compiler? 如何保持预期的功能并满足我的编译器要求? First time doing this. 第一次这样做。

EDIT: I feel like I've been misunderstood. 编辑:我觉得我被误解了。 I want to pass a class as the parameter under which the condition is checked. 我想通过一个类作为检查条件的参数。 I commented the code to clarify this. 我评论了代码以澄清这一点。

If passing the parameter as type Class is bullshit for this, just say so. 如果为此将参数传递为Class类型是胡说八道,那就这么说。 It was an idea, because I don't know how to pass a class as parameter. 这是一个主意,因为我不知道如何将类作为参数传递。

You want clazz.isAssignableFrom(instance.getClass()) . 您需要clazz.isAssignableFrom(instance.getClass()) This returns true if instance has type clazz or is a subtype of type clazz . 这将返回true ,如果instance有型clazz或类型的子类型clazz

Edit: here's a more complete example. 编辑:这是一个更完整的示例。 You have a Person class and some subclasses: 您有一个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);
    }
}

Then you use your code with my suggested edit: 然后,将您的代码与我建议的编辑一起使用:

public void printPersonTypeSet(Class<?> clazz) {
    for (Person instance : personSet)
        if (clazz.isAssignableFrom(instance.getClass()))
            System.out.println(instance);
}

If personSet is initialized as: 如果personSet初始化为:

Set<Person> personSet = new HashSet<Person>();
personSet.add(new GoodPerson("Good1"));
personSet.add(new GoodPerson("Good2"));
personSet.add(new BadPerson("Bad1"));

then you can find the instances of GoodPerson by using printPersonTypeSet(GoodPerson.class) . 然后您可以使用printPersonTypeSet(GoodPerson.class)查找GoodPerson的实例。 (Note this will also find subclasses of GoodPerson .) (请注意,这也会找到GoodPerson子类。)

In your example clazz is an instance of Class , and that's probably not what you want to give as parameter in your method. 在您的示例中, clazzClass的实例,而这可能并不是您想要在方法中提供的参数。 So you're asking your compiler if instance is an instance of clazz , which it can't be as clazz is not a class but an instance. 因此,您要问编译器instance是否是clazz的实例,而不能因为clazz不是类而是实例而不能成为clazz的实例。

The best would be using the isInstance(Class) method. 最好的方法是使用isInstance(Class)方法。 According to the Java documentation This method is the dynamic equivalent of the Java language instanceof operator. 根据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);
}

From Java doc: 从Java文档:

Determines if the specified {@code Object} is assignment-compatible with the object represented by this {@code Class}. 确定指定的{@code对象}是否与此{@code类}表示的对象赋值兼容。 This method is the dynamic equivalent of the Java language {@code instanceof} operator. 此方法动态等效于Java语言{@code instanceof}运算符。 The method returns {@code true} if the specified {@code Object} argument is non-null and can be cast to the reference type represented by this {@code Class} object without raising a {@code ClassCastException.} It returns {@code false} otherwise. 如果指定的{@code Object}参数为非null,并且可以强制转换为此{@code Class}对象表示的引用类型,而无需引发{@code ClassCastException。},则该方法返回{@code true}。它返回{ @code false},否则。

Method Signature 方法签名

public native boolean isInstance(Object obj)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM