Check if object has method in Java?

Issue

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.

Solution

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.

Answered By – duffymo

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published