Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if object has method in Java?

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.

like image 680
Connor Deckers Avatar asked May 26 '12 23:05

Connor Deckers


People also ask

How do you check if a method exists in a class Java?

Use the typeof operator to check if a method exists in a class, e.g. if (typeof myInstance. myMethod === 'function') {} . The typeof operator returns a string that indicates the type of the specific value and will return function if the method exists in the class.

How do you identify a method in Java?

While defining a method, remember that the method name must be a verb and start with a lowercase letter. If the method name has more than two words, the first name must be a verb followed by an adjective or noun. In the multi-word method name, the first letter of each word must be in uppercase except the first word.

How do you find the method object?

getMethod() returns a Method object that reflects the specified public member method of the class or interface represented by this Class object. The name parameter is a String specifying the simple name of the desired method.

How do you check if an object is an interface in Java?

isInterface() method The isArray() method of the Class class is used to check whether a class is an interface or not. This method returns true if the given class is an interface. Otherwise, the method returns false , indicating that the given class is not an interface.


1 Answers

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.

like image 58
duffymo Avatar answered Oct 06 '22 01:10

duffymo