简体   繁体   English

基于参数的通用转换

[英]generic cast based on param

I need a "generic" cast based on a method param (className).我需要一个基于方法参数(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".所以我想将“o”直接转换为“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.在您的情况下,您似乎已经将类名作为String ,在这种情况下, ManoDestra 的答案将是合适的。 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有关更多详细信息,请参阅此回复: https : //stackoverflow.com/a/2127384/5969411

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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