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?
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 class name be used as argument? Yes.
We can pass an object to a JavaScript function, but the arguments must have the same names as the Object property names.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With