Check if object has method in Java?
Solution 1
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.
Solution 2
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.
Solution 3
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).
Solution 4
First, define an interface that will require all objects implementing it to implement a setAlpha()
method:
public interface AlphaChanger {
public void setAlpha(int alpha); // concrete classes must implement this
}
Then, define classes that implement this interface:
public class Thing implements AlphaChanger {
public void setAlpha(int alpha) { // must be present
// implementation
}
}
Now you can require that all objects passed to your method must implement the AlphaChanger
interface:
public void yourMethod(AlphaChanger changer) {
changer.setAlpha(10); // you know for sure the method exists
}
Connor Deckers
Connor is a Software Developer specialising in Javascript, having developed several in-house toolings and projects. These include a major Chrome browser extension that augments our internal LMS, and several supporting toolsets for in-house use.
Updated on June 22, 2022Comments
-
Connor Deckers almost 2 years
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 aTextView
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.