1

I need a "generic" cast based on a method param (className). Something like this:

void save(DomainObject o, String className) {
    doSomething((className) o);
}

So I want to cast "o" right into an Object of the class "className".

I know how to instantiate an Object via the classname String, but are there any easy possibilities to manage my casting problem?

  • I like to use interfaces in cases like this. So your object ```o``` should implement the interface – Victor Apr 01 '16 at 19:29

2 Answers2

1

In your case it seems you already have the class name as a String, in which case the answer by ManoDestra would be suitable. As an alternative though, you could also use this approach:

void save(DomainObject o, Class<?> type){       
    doSomething( type.cast(o) );
}

And then you'd call it like this:

save( myObject, Integer.class );
Magnus
  • 17,157
  • 19
  • 104
  • 189
0

You can use Reflection to do this...

void save(DomainObject o, String className) {
    Class<?> clazz = Class.forName(className);
    doSomething(clazz.cast(o));
}

You'll need to handle the potential class cast exception, but I'm sure you can manage that :)

See this response for further details: https://stackoverflow.com/a/2127384/5969411

Community
  • 1
  • 1
ManoDestra
  • 6,325
  • 6
  • 26
  • 50