如何基于调用类的名称实现Java方法,该方法将调用另一个方法? [英] How to implement a Java method, that will call another method, based on the name of the calling class?

查看:139
本文介绍了如何基于调用类的名称实现Java方法,该方法将调用另一个方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个Java类,WebCenterGrid.此类包含在网格中执行操作的方法,例如查找行,查找单元格值,对列进行排序.我们有几个使用此类的类.所有使用它的类都引用不同的网格,但是功能是相同的.

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.

唯一不同的是如何创建网格.某些类进行填充网格的搜索(搜索也会刷新).有些会执行updateList()来更新网格等.

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.

我想向WebCenterGrid添加一种方法来刷新网格.问题是,正如我所说的,每种方法都有不同的名称.

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.

我不知何故想要将要进行刷新的方法的名称传递给WebCenterGrid.我进行了一些搜索,发现了一些关于lambda的东西,我并不太了解.

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.

我已经有一段时间没有使用C ++了,但是有某种方法可以将方法传递给这些方法.此类是使用Java而不是C ++编写的,但是有某种可以理解的等效方法吗?

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();
    }
 }

推荐答案

基本上,有两种方法.

一种方法是使用 reflection ,这意味着:依赖运行时类型信息,该信息通常是从原始字符串派生的.就像说:我有一个类X的对象,并且我想在该对象上调用名为"doTheFoo()"的方法.

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.

一种更好的方法是使用 MethodHandle 类,而不是原始"反射Method类.有关句柄,请参见此处.

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.

这篇关于如何基于调用类的名称实现Java方法,该方法将调用另一个方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆