Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, dynamic cast, pass value from Object to object of target Class

I'm looking for a simple solution to pass values of attributes/objects between two java programs. The programs are identical (running on separated nodes) and can't set/get variables though call of method. They can communicate only through external channel like file or network. There are many various objects which should be shared. My idea is to pass the data as text and encode/decode with xml. I can also send a name of object and its class.

My problem is: the decode method returns variables of type Object. I've to move the value to the target object but without cast I'm getting compiler error 'incompatible cast'. So I've to do a cast. But there are many possible objects and I've to do a huge set of if or switch statement. I have the name of class and it would be so nice to do some kind of dynamic cast.

This thread discuss similar topic and suggest to use Class.cast() but I've got no success:

java: how can i do dynamic casting of a variable from one type to another?

I you prefer code oriented question here you are:

  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

like image 537
Annie W. Avatar asked Oct 21 '22 11:10

Annie W.


1 Answers

If your problem is with the assign instruction commented within your code sample, you could implement something with generics:

public <T> T decode(String str) {
    ... decode logic
    return (T)decodedObject;
}

This approach could let you do something like:

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;
}
like image 71
Francisco Spaeth Avatar answered Oct 24 '22 04:10

Francisco Spaeth