对一个通过反射进行排序的分析
在百度知道看到的,顺便回答了,在这也留一份。
百度知道:http://zhidao.baidu.com/question/216983013.html
我为了方便解释、写了一个测试类
首先调用test,传递一个method过去;
通过反射机制(这里用到了getMethod、invoke,我比较喜欢getField)、获取到m1对象的getName方法,getMethod第一个参数为方法名、第二个是给这个method的参数的类型,
If parameterTypes is null, it is treated as if it were an empty array,如果为null,表示没有参数;(即 getName()方法);
然后在通过 invoke 注入参数;第一个是相应对象的引用、第二个是参数值(刚刚的是类型,现在才是值);
If the underlying method is static, then the specified obj argument is ignored. It may be null,也就是说static的方法第一个参数是null;
我们要调用的是getName(),那么就是 m1.invoke(model,null)了;
执行结果为:my name ;相当于调用了getName()方法.
绕了一圈也就是 model.getName() == model.getClass().getMethod("getName",null).invoke(model,null);
对于有参数的,调整为
结果:can you
接下来上边的题目就简单了,
public void Sort(List<E> list, final String method, final String sort){
这里给出了method,接下来是一个内部类的处理;自定义一个comparator,
Method m1 = ((E) a).getClass().getMethod(method, null);
这里就是获取method方法,他没有参数。
m1.invoke(((E)a), null).toString()
这里是得到对象a调用方法method之后的返回值。
ret = m1.invoke(((E)a), null).toString().compareTo(m2.invoke(((E)b), null).toString());
而这里就是比较两个对象method方法的返回值
将ret交给sort进行排序;
在百度知道看到的,顺便回答了,在这也留一份。
百度知道:http://zhidao.baidu.com/question/216983013.html
我为了方便解释、写了一个测试类
/** test for reflex */
public class Model {
private String name;
private String content;
public Model(){
this.name = "my name";
this.content = "a long text";
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getContent() {
return content;
}
//测试
public void test() throws Exception{
Model model = new Model();
Method m1 = model.getClass().getMethod("getName", null);
System.out.println(m1.invoke(model, null));
}
public static void main(String args[]){
try {
new Model().test("getName");
} catch (Exception e) {
e.printStackTrace();
}
}
}
首先调用test,传递一个method过去;
通过反射机制(这里用到了getMethod、invoke,我比较喜欢getField)、获取到m1对象的getName方法,getMethod第一个参数为方法名、第二个是给这个method的参数的类型,
If parameterTypes is null, it is treated as if it were an empty array,如果为null,表示没有参数;(即 getName()方法);
然后在通过 invoke 注入参数;第一个是相应对象的引用、第二个是参数值(刚刚的是类型,现在才是值);
If the underlying method is static, then the specified obj argument is ignored. It may be null,也就是说static的方法第一个参数是null;
我们要调用的是getName(),那么就是 m1.invoke(model,null)了;
执行结果为:my name ;相当于调用了getName()方法.
绕了一圈也就是 model.getName() == model.getClass().getMethod("getName",null).invoke(model,null);
对于有参数的,调整为
public void test(String method) throws Exception{
Model model = new Model();
Method m1 = model.getClass().getMethod(method, String.class);
m1.invoke(model, "can you");
System.out.println(model.getName());
}
结果:can you
接下来上边的题目就简单了,
public void Sort(List<E> list, final String method, final String sort){
这里给出了method,接下来是一个内部类的处理;自定义一个comparator,
Method m1 = ((E) a).getClass().getMethod(method, null);
这里就是获取method方法,他没有参数。
m1.invoke(((E)a), null).toString()
这里是得到对象a调用方法method之后的返回值。
ret = m1.invoke(((E)a), null).toString().compareTo(m2.invoke(((E)b), null).toString());
而这里就是比较两个对象method方法的返回值
将ret交给sort进行排序;