繁体   English   中英

如何在两个不同的类中设置相同的属性?

[英]How can I set same Property in two different classes?

我有两个 java 类。 一些属性具有相同的名称。 但是这些类是生成的,所以我不能将属性放在父 class 中。

是否有可能使用一种方法只设置一次相同的属性?

Class A {
  String Same1 = "";
  String Same2 = "";
  String AOther1 = "";
  String AOther2 = "";
}

Class B {
  String Same1 = "";
  String Same2 = "";
  String BOther1 = "";
  String BOther2 = "";
}

这是我不想要的:

{
  a.setSame1("xyz");
  a.setSame2("xyz");
  a.setAOther1("xyz");
  a.setAOther2("xyz");

  b.setSame1("xyz");
  b.setSame2("xyz");
  b.setBOther1("xyz");
  b.setBOther2("xyz");
}

我想这样做:

private Object same(String iClass) {
  Object ret = null;
  if ("A".equals(iClass)) {
    ret = new A();
  }
  if ("B".equals(iClass)) {
    ret = new B();
  }
  ret.setSame1("xyz");  <-- Here I get "cannot find symbol". Object has no "same1" property
  ret.setSame2("xyz");
  return ret;
}

{
  A a = this.same("A");
  a.setAOther1("xyz");
  a.setAOther2("xyz");

  B b = this.same("B");
  b.setBOther1("xyz");
  b.setBOther2("xyz");
}

感谢你的帮助!

我找到了一个非常简单的解决方案。 反思不起作用。

Class<?> c = returnObj.getClass();
Method method = c.getDeclaredMethod("setSame1", String.class);
method.invoke(returnObj, "Here a Test");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM