简体   繁体   中英

generic cast based on param

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM