Java, dynamic conversion, transfer value from object to object of target class

I am looking for a simple solution to pass attribute / object values ​​between two java programs. The programs are identical (work on separate nodes) and cannot set / receive variables, although the method is called. They can only communicate through an external channel, such as a file or network. There are many different objects that need to be separated. My idea is to transfer data as text and encode / decode using xml. I can also send the name of the object and its class.

My problem: the decode method returns variables of type Object. I have to move the value to the target, but without a cast I get a "incompatible cast" compiler error. So I have to do the cast. But there are many possible objects, and I have to make a huge set of if or switch statements. I have a class name, and it would be nice to make some kind of dynamic throw.

This thread discusses a similar topic and suggests using Class.cast (), but I have not succeeded:

java: how can I dynamically cast a variable from one type to another?

I would prefer a code oriented question here:

  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

Cheers, Annie

+5
source share
4 answers

assign, , - generics:

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;
}
+3

generics:

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);

, - .

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");

}
0

All Articles