Check if the object has a method in Java?

I don’t know much about Java, I know enough to get me through to the end, but I'm not perfect yet, so I apologize if this is a stupid question.

I am trying to write a class that might have some kind of object passed to it, but I need to check if it has passed a specific method. How can I check this?

Hope this makes sense. Greetings.

EDIT

Thanks for all the quick answers! I'm not too familiar with interfaces, etc., so I'm not quite sure how to use them. But, in order to better understand what I'm doing, I am trying to create a class that will affect the alpha of the object, for example. ImageView or TextView , for example. How can I create an interface for this without listing each object individually, when all I need to do is make sure they have a .setAlpha() method? Does this make sense? Greetings.

+4
source share
5 answers

A better idea would be to create an interface with this method and make this type of parameter. Each object passed to your method will need to implement this interface.

This is called expressing your contract with customers. If you need this method, say so.

+14
source

Get the instance class with Object.getClass() , then use Class.getMethod(String, Class...) and catch a NoSuchMethodException if the class does not have this method.

On the other hand, this is not a good practice in Java. Try using interfaces instead.

+7
source

You can do this using Java reflection.

Something like object.getClass().getMethods() to get an array of Method objects, or you can use getMethod() to get an object with a specific name (you must define the parameters).

+2
source

First, define an interface that requires all objects that implement it to implement the setAlpha() method:

 public interface AlphaChanger { public void setAlpha(int alpha); // concrete classes must implement this } 

Then define the 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 } 
+2
source

You can try and list class methods like this (example: FooBar class):

 Class fooBar= FooBar.class; Method[] methods = fooBar.getDeclaredMethods(); if (methods.length == 0){ ... } else{ ... } 
0
source

Source: https://habr.com/ru/post/1414554/


All Articles