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.
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.
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.
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.
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.
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.
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