Java – class as function parameter

I have a function to filter the list of some values. It uses instanseof to construct:

public static List<View> getAllChildren(View v) {
    /* ... */
    if (v instanceof Button) {
        resultList.add(v);
    }
    /* ... */
 }

I want to make it more general and set the button as the function parameter:

public static List<View> getAllChildren(View v,? myClass) {
    /* ... */
    if (v instanceof myClass) {
        resultList.add(v);
    }
    /* ... */
 }

But I don't know how to pass MyClass to the function Please tell me how to summarize this function?

Solution

You can use the class class to pass the class type as a parameter Note that it is a generic type In addition, the instanceof operator is only applicable to reference types, so you must flip it to make it work:

public static List<View> getAllChildren(View v,Class<?> myClass) {
    /* ... */
    if (myClass.isinstance(v)) {
        resultList.add(v);
    }
    /* ... */
}

To pass the class type like this, you can simply use the name of the class you want and append ". Class" For example, if you want to call this method with the button class, you will do this:

getAllChildren(view,Button.class);

Or, if you have an instance of the class you want, you will use the getClass () method:

Button b = new Button();
getAllChildren(view,b.getClass());

As Evan LaHurd mentioned in his comments, isinstance() will check whether these two classes are compatible with assignment, so they may not be exactly the same class If you want to ensure that they are identical classes, you can check whether they are identical, as follows:

myClass.equals(v.getClass());

or

myClass == v.getClass();

Just like bayou As IO points out, it also works in this case

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>