我有一个Parent.class(User和Element可以被任何类替换)
public abstract class Parent {
User user;
public void InitUser() {
Fileds f = this.getClass().getDeclaredFields();
for(int i=0; i<f.length; i++) {
f[i].set(this, new Element(i));
}
}
}
子类
public class Child extends Parent {
Element e1;
Element e2;
public Child(User user) {
super();
this.user = user;
}
public void doSomethingUsingE1AndE2() {
// do something by using e1 and e2, invoking user's methods.
user.perform(e1);
user.perform(e2);
}
}
在我的Client.class中,以下两种构造和使用Child的方式有什么区别吗?
1.
public class Client() {
User user = new User();
Class childClass = Class.forName("com.xxx.Child");
Constructor con = childClass .getConstructor(User.class);
Object o = con.newInstance(user);
Method initMethod = child.getSuperclass().getDeclaredMethod(
"InitUser");
initMethod.invoke(o);
Method keyMethod = child.getMethod("doSomethingUsingE1AndE2");
keyMethod.invoke(o);
}
2.
public class Client() {
User user = new User();
Child c = new Child(user);
c.InitUser();
c.doSomethingUsingE1AndE2();
}
非常感谢。
最佳答案
创作上没有什么区别。一种是标准方式(新),另一种是 Reflection
.
但请记住
Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.
性能开销
安全限制
内部结构暴露
总是尝试使用新的方式,除非你没有其他选择去反射。
关于java - 这两种构造实例方式的区别(Reflect 和 new),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33077008/