gpt4 book ai didi

java - 这两种方式构造实例的区别(Reflect和new)

转载 作者:行者123 更新时间:2023-11-30 08:08:35 25 4
gpt4 key购买 nike

我有一个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.

  • 性能开销

  • 安全限制

  • 内部结构暴露

总是尝试使用新的方式,除非你别无选择去反射(reflection)

关于java - 这两种方式构造实例的区别(Reflect和new),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33077008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com