Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class as function argument

Tags:

java

I have a function that filtering list of some values and it use instanseof construction:

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

I want to make it more general and set Button as 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 i can generalize this function?

like image 276
Letfar Avatar asked Sep 14 '15 21:09

Letfar


People also ask

Can we pass class as function arguments?

In C++ we can pass class's objects as arguments and also return them from a function the same way we pass and return other variables.

Can you pass a class as an argument in Python?

can class name be used as argument? Yes.

Can we pass class objects as function arguments in JavaScript?

We can pass an object to a JavaScript function, but the arguments must have the same names as the Object property names.

How do you write a function as an argument?

Functions are data, and therefore can be passed around just like other values. This means a function can be passed to another function as an argument. This allows the function being called to use the function argument to carry out its action.


1 Answers

You can pass a class type as a parameter using the Class class. Note that it is a generic type. Also, the instanceof operator works only on reference types, so you will have to flip it around to get this to work:

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

In order to get the Class type to be passed in like this, you can simply use the name of the class you want, with ".class" appended. For example, if you wanted to call this method with the Button class, you would do it like so:

getAllChildren(view, Button.class);

Or if you had an instance of something that you wanted the class of, you would use the getClass() method:

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

As Evan LaHurd mentioned in a comment, isInstance() will check if the two classes are assignment-compatible, so they may not be the exact same class. If you want to make sure they are exactly the same class, you can check them for equality like so:

myClass.equals(v.getClass());

or

myClass == v.getClass();

will also work in this case, as pointed out by bayou.io

like image 64
gla3dr Avatar answered Sep 23 '22 03:09

gla3dr