How to implement a Java method, that will call another method, based on the name of the calling class?

Tony :

We have a Java class, WebCenterGrid. This class is full of methods to do things in a grid such as finding a row, finding a cell value, sorting a column. We have several classes that use this class. The classes using it all refer to different grids, but the functionality is the same.

The only thing that differs is how to create the grid. Some classes do a search which populates the grid (search also refreshes). Some do an updateList() to update the grid, etc.

I would like to add a method to WebCenterGrid to refresh the grid. The problem is as I said each method has a different name.

I somehow want to pass into WebCenterGrid the name of a method to call to do the refresh. I have done some searches and found something about lambda which I did not really understand.

I haven't used C++ in a while but there was some way to pass a method into those methods. This class is in Java not C++, but is there some sort of understandable equivalent?

 public class WebCenterGrid {
    ....
    ....
    public void refresh(Method meth) {
           meth();
    }
 }
GhostCat salutes Monica C. :

Basically, there are two ways.

One is to use reflection, this means: relying on runtime type information, commonly derived from raw strings. Like saying: I have some object of class X, and I want to invoke the method named "doTheFoo()" on that object.

See here for all the glory details.

A slightly better way is to use the MethodHandle class, instead of the "raw" reflection Method class. See here for handles.

But then: reflection is happening at runtime. Your code compiles fine, but if you get any detail wrong, it blows up at runtime.

Thus I suggest looking into lambdas, based on Function, see here.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=102073&siteId=1