【发布时间】:2016-10-05 05:40:59
【问题描述】:
说,我有课。
class Person{
private int id;
private String name;
public void setId(int id){
this.id = id;
}
public void setName(String name){
this.name = name;
}
public int getId(){
this.id = id;
}
public String getName(){
this.name = name;
}
}
像这样,我有不止一个数据传输类。我希望有一个类,它将动态采用方法name(String.class)和参数value(Object.class),如下面的sn-p所示。
class Mapper{
private Person person = new Person();
private Method method = null;
public void map(String methodName, Object parameterValue){
// 1. Get the method using methodName.
// 2. Get the method's parameter type.
// 3. Type cast 'parameterValue' to parameter type.
// 4. Call the method on 'person' object by passing type cast value
// from the 3-step(above).
}
}
我试过搜索它。我得到了 Reflection API 的结果,如下面的 sn-p 所示。
Class<String> clz = String.class;
for (Method m : clz.getDeclaredMethods()) {
System.err.println(m.getName());
int paramCount = m.getParameterTypes().length;
for (int i = 0; i < paramCount; i++) {
System.err.println(" arg" + i);
}
}
但是,这种方法不能满足我的需要。希望你能理解。
【问题讨论】:
-
Reflection API 将是要走的路。不过,这似乎是一个阴暗的设计。
map的目的又是什么? -
为什么不能满足你的需求?
-
你想在哪个类上动态调用方法?
-
谢谢大家。我明白了。
标签: java methods reflection parameters