5

我正在寻找一个简单的解决方案来在两个 java 程序之间传递属性/对象的值。这些程序是相同的(在分离的节点上运行)并且不能通过调用方法来设置/获取变量。他们只能通过文件或网络等外部渠道进行通信。有许多不同的对象应该共享。我的想法是将数据作为文本传递并使用 xml 进行编码/解码。我还可以发送对象及其类的名称。

我的问题是:decode 方法返回 Object 类型的变量。我必须将值移动到目标对象但没有强制转换我得到编译器错误'不兼容的强制转换'。所以我要做一个演员表。但是有很多可能的对象,我必须做大量的 if 或 switch 语句。我有班级的名字,做某种动态演员真是太好了。

该线程讨论了类似的主题并建议使用 Class.cast() 但我没有成功:

java:如何将变量从一种类型动态转换为另一种类型?

我你更喜欢面向代码的问题,你是:

  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

干杯,安妮

4

4 回答 4

3

如果您的问题与代码示例中注释的分配指令有关,您可以使用泛型实现一些东西:

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;
}
于 2013-04-27T13:30:36.043 回答
0

如果您已经在传递 XML,那么为什么不使用 JAXB 来编组和解组文本

http://docs.oracle.com/javase/tutorial/jaxb/intro/examples.html

但是如果你说两个程序都是java,那么使用RMI

http://www.javacoffeebreak.com/articles/javarmi/javarmi.html

http://docs.oracle.com/javase/6/docs/technotes/guides/rmi/hello/hello-world.html

于 2013-04-27T13:30:21.460 回答
0

您可以使用泛型:

public static <T> T decode(Class<T> c, String str) {
  return (T)str;
}

...

Class<?> c = Class.forName(className); // throws CNFE
out = decode(String.class, in);

当然,您的解码方法需要做的还不止这些。

于 2013-04-27T13:35:12.463 回答
0

你可以去做这样的事情

public static <T> T decode(T obj) {

    return (T)(obj);
}



public static void main(String [] args){
    Integer int1 = decode(123);
    String str1 = decode("abc");

}
于 2013-04-27T14:03:00.330 回答