我有以下问题,并想知道是否有有效的解决方案。 (我正在使用Java)来自不同类的通用数据提取
想象一下,您有多种不同类型的类,它们在具有不同名称的变量中保存相同的数据并考虑给出。
这里的示例: 想象有一个容器类
- 短颜色
- INT大小
- 字符串形状
内三个经验值作为构件,并考虑两个类
- 的Class1
- 的Class2
Class1的有三个成员变量是所述经验值:
- 短RGB_COLOR - >对应于颜色
- 长就是大型 - >对应于就是大型
- 字符串轮廓 - >对应形状
Class2中有三个成员变量是所述经验值:
- INT CMYK - >对应于颜色
- INT伟大 - >对应于就是大型
- 字符串shapecountour - >对应于形状
正如你看到的名字是不同的。所以,如果我想从第一和第二类导入容器类的值,我需要 自己转换每个参数,以便将其添加到容器类,因此我需要键入因为有成员变量(这里6) 例如看到这个伪代码的导入功能:
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;
}
现在想象一下问题,其中有更多的参数。 是否有一种通用的方法来解决导入问题,并逐个为每个成员执行?
谢谢你的帮助。
编辑:感谢您的快速答案。 正如我所说我不能修改class1和class2。
我检查了反射,他们有这个例子来改变字段。
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();
}
}
}
但我仍需要通过名称例如调用每个变量“章”。 我得到什么错误?