【发布时间】:2012-08-17 12:29:15
【问题描述】:
我有以下问题,想知道是否有有效的解决方案。 (我正在使用 Java)
假设您有多个不同类型的类在不同名称的变量中保存相同的数据,并考虑这一点。
这里是一个例子: 想象一下容器类中有三个经验值作为成员
- 短颜色
- int 大小
- 字符串形状
并考虑这两个类
- class1
- 2 类
class1 有三个成员变量作为经验值:
- short rgb_color -> 对应颜色
- long bigness -> 对应于 bigness
- 字符串轮廓 -> 对应形状
class2 有三个成员变量作为经验值:
- int cmyk -> 对应颜色
- int greatness -> 对应于 bigness
- 字符串 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();
}
}
}
但我仍然需要按名称调用每个变量,例如“章节”。 我怎么了?
【问题讨论】:
标签: java class generics import