'How can I set same Property in two different classes?

I have two java classes. Some of the properties have the same name. But these classes are generated so I can't put the properties in a parent class.

Is there are possibility to use a method to set same properties only one time?

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

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

this I don't want:

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

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

I want to do it like this:

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");
}


Solution 1:[1]

Thanks all for your help!

I found a solution that is very easy. Reflections not work.

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Burner