I have the following problem and wonder whether there is an efficient solution to it. (I am using Java)
Imagine you have multiple different types of classes holding the same data in variables with different name and consider this given.
Here an example: Imagine there are the three empiric values as member within a container class
- short color
- int size
- String shape
and consider the two classes
- class1
- class2
class1 has three member variables being the empiric values:
- short rgb_color -> corresponds to color
- long bigness -> corresponds to bigness
- String contour -> corresponds to shape
class2 has three member variables being the empiric values:
- int cmyk -> corresponds to color
- int greatness -> corresponds to bigness
- String shapecountour -> corresponds to shape
As you see the names are different. So if I want to import the values from class one and two into the container class, I would need to convert every parameter by itself in order to add it to the container class and thus I need to type as there are member variables (here 6) e.g. see this pseudo code for the import function:
public void import(class1 class){
this.color = (short) class.rgb_color;
this.size = (int) class.bigness;
this.shape = (String) class.contour;
}
public void import(class2 class){
this.color = (short) class.cmyk;
this.size = (int) class.greatness;
this.shape = (String) class.shapecontour;
}
Now imagine problems, where there are much more parameters. Is there a generic way to solve the import as to do it one by one for each member?
Thank you for your help.
EDIT: Thanks already for the fast answers. As I said I cannot modify class1 and class2.
I have checked the reflection, where they have this example for changing the fields.
public class Book {
public long chapters = 0;
public String[] characters = { "Alice", "White Rabbit" };
public Tweedle twin = Tweedle.DEE;
public static void main(String... args) {
Book book = new Book();
String fmt = "%6S: %-12s = %s%n";
try {
Class<?> c = book.getClass();
Field chap = c.getDeclaredField("chapters");
out.format(fmt, "before", "chapters", book.chapters);
chap.setLong(book, 12);
out.format(fmt, "after", "chapters", chap.getLong(book));
Field chars = c.getDeclaredField("characters");
out.format(fmt, "before", "characters",
Arrays.asList(book.characters));
String[] newChars = { "Queen", "King" };
chars.set(book, newChars);
out.format(fmt, "after", "characters",
Arrays.asList(book.characters));
Field t = c.getDeclaredField("twin");
out.format(fmt, "before", "twin", book.twin);
t.set(book, Tweedle.DUM);
out.format(fmt, "after", "twin", t.get(book));
// production code should handle these exceptions more gracefully
} catch (NoSuchFieldException x) {
x.printStackTrace();
} catch (IllegalAccessException x) {
x.printStackTrace();
}
}
}
But still I need to call each variable by name as e.g. "chapters". What do I get wrong?