动态调用方法 [英] Dynamically invoke methods
问题描述
我在这里需要一点帮助,如果您知道如何解决我的问题,请告诉我.
I need a little bit of help here, tell me if you have any idea how to solve my problem.
假设我有这门课:
public testClass{
public int example1(){
return 2;
}
public int example2(){
return 0;
}
public int example3(){
return 456;
}
}
我想要一个方法和这个方法做同样的事情,但是以动态的方式
I want a method which will do the same thing that this method, but in a dynamic way
public int methodeSwitch(int a){
if (a==1){return method1;}
if (a==2){return method2;}
if (a==3){return method3;}
return null;
}
我的问题是我有一个包含 50 多个字段的大型类 (dto),所以我想根据我目前使用的字段来使用 getter 和 setter(所以是的,动态的).我知道如何访问字段(使用 java.lang.Field,wouuu),但我不知道如何按名称强制转换方法(将动态创建).
My problem is that I have a huge class (dto) with 50+ fields, so i'd like to use getters and setters depending on the fields that i use at the moment (so yeah, dynamically). I know how to access fields (with java.lang.Field, wouuu), but i have no clue on how I could cast a method by its name (which will be created dynamically).
只要给我一个提示就太棒了!
Just giving me a hint would be amazing!
谢谢法比安
澄清一下,我必须编写一个方法,它基本上使用我班上的每个 setter,所以如果我可以使用类似
to clarify, I have to write a method who basically use every setters of my class, so if I could use something like
useMethod("set"+fields[i]+"();");
这会很有帮助,并且可以防止我编写数十行代码.
That would be helpful and prevent me from writing dozens of lines of code.
再次感谢帮助的人!;)
Thanks again for the ones helping! ;)
推荐答案
您需要使用反射从您的类中获取声明的方法.我假设这些方法存在于您想要调用 getter/setter 的类中,并且 fields
是字段名称的 String[]
.
You need to use reflection to get the declared method from you class. I have assumed that these methods live in the class on which you want to invoke the getter/setter and that fields
is a String[]
of field names.
private Object callGet(final String fieldName) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
final Method method = getClass().getDeclaredMethod("get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1));
return method.invoke(this, (Object[]) null);
}
private void callSet(final String fieldName, final Object valueToSet) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
final Method method = getClass().getDeclaredMethod("set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1), new Class[]{valueToSet.getClass()});
method.invoke(this, new Object[]{valueToSet});
}
你也可以看看 Commons BeansUtil 这是一个设计的库正是为了做到这一点...
You could also have a look at Commons BeansUtil which is a library designed for doing exactly this...
这篇关于动态调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!