项目中用到了java的反射,可以大大减少代码量。但是反射的性能却不容乐观,做了个简单的测试,如下。
public void noreflect() { Person p = new Person(); for(int i=0; i<10000000; ++i){ Person.setName(p, "name"); Person.setAge(p, "22"); } } @Test public void reflect(){ Person p = new Person(); try { for(int i=0; i<10000000; ++i){ Method setname = Person.class.getDeclaredMethod("setName", Person.class, String.class); Method setage = Person.class.getDeclaredMethod("setAge", Person.class, String.class); setname.invoke(null, p, "name"); setage.invoke(null, p, "22"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }