Reputation: 2507
I'm not all too greatly experienced with Java, I know enough to get me through at the moment, but I'm not perfect yet, so I apologize if this is a dumb question.
I'm trying to write a class that can have any sort of object passed to it, but I need to check if the object passed has a particular method with it. How would I go about testing this?
I hope this makes sense. Cheers.
EDIT
Thanks for all the fast replies! I'm not too familiar with interfaces etc, so I'm not entirely sure how to use them. But, to give a better insight into what I'm doing, I'm trying to create a class that will affect the alpha of an object, e.g. ImageView
or a TextView
for instance. How would I create an interface for that, without listing each object individually, when all I need is to make sure that they have the method .setAlpha()
? Does this make sense? Cheers.
Upvotes: 6
Views: 23246
Reputation: 51
Those who say that you should use an interface(superclass) declaring the required method are right. This way we test if an object is instance of it, cast and invoke.
Fortunately, setAlpha(float a) is already defined in android.view.View class - super of both TextView and ImageView. So the simplest and fastest:
import android.view.View;
.......
if(object instanceof View) ((View)anObject).setAlpha(a);
Sometimes it happens we have java.lang.reflect.Method, and want to check if it can be invoked on some object:
Method m;
.....
try {
if(m.getDeclaringClass().isInstance(anObject)) m.invoke(anObject);
} catch(IllegalAccessException | IllegalArgumentException | InvocationTargetException ex){ ... }
The principle is the same, plus a little extra effort due to reflection using.
Upvotes: -1
Reputation: 308878
A better idea would be to create an interface with that method and make that the parameter type. Every object passed to your method will have to implement that interface.
It's called expressing your contract with clients. If you require that method, say so.
Upvotes: 16
Reputation: 15070
You can try and list the classes' methods like this (example : FooBar class):
Class fooBar= FooBar.class;
Method[] methods = fooBar.getDeclaredMethods();
if (methods.length == 0){
...
} else{
...
}
Upvotes: 0
Reputation: 19443
You can do this using Java reflection.
Something like object.getClass().getMethods()
to get an array of the Method
objects, or you can use the getMethod()
to get an object with a particular name (you have to define the parameters).
Upvotes: 3
Reputation: 43862
Get the instance's class with Object.getClass()
, then use Class.getMethod(String, Class...)
and catch a NoSuchMethodException
if the class doesn't have that method.
On the other hand, this is not a very good practice in Java. Try using interfaces instead.
Upvotes: 8