我正在寻找一种简单的解决方案来在两个 Java 程序之间传递属性/对象的值。这些程序是相同的(在不同的节点上运行)并且不能通过调用方法设置/获取变量。他们只能通过文件或网络等外部 channel 进行通信。有许多不同的对象应该共享。我的想法是将数据作为文本传递并使用 xml 进行编码/解码。我还可以发送对象名称及其类。
我的问题是:解码方法返回对象类型的变量。我必须将值移动到目标对象,但没有强制转换,我收到编译器错误“不兼容的强制转换”。所以我必须做 Actor 。但是有很多可能的对象,我必须做大量的 if 或 switch 语句。我有类(class)的名字,做一些动态转换会很好。
这个线程讨论了类似的主题并建议使用 Class.cast() 但我没有成功:
java: how can i do dynamic casting of a variable from one type to another?
我在这里你更喜欢面向代码的问题:
Object decode( String str )
{
return( str );
}
String in = "abc";
String out;
// out = decode( in ); // compiler error 'incompatible types'
// out = (String)decode( in ); // normal cast but I'm looking for dynamic one
// out = ('String')decode( in ); // it would be perfect
干杯, 安妮
最佳答案
如果您的问题出在您的代码示例中注释的赋值指令,您可以使用泛型实现一些东西:
public <T> T decode(String str) {
... decode logic
return (T)decodedObject;
}
这种方法可以让你做类似的事情:
public void foo1(String bar) {
String s = decode(par);
}
public void foo2(String bar) {
Integer s = decode(par);
}
<T> T decode(String serializedRepresentation) {
Object inflatedObject;
// logic to unserialize object
return (T)inflatedObject;
}
关于Java,动态转换,将值从对象传递到目标类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16252639/