非常简单的Java动态强制转换
简单的问题,但我用了一个多小时。 我的代码如下。 我需要使SomeClass sc动态化。 因此,您将类名作为字符串传递给函数,并使用该类代替静态someClass。 怎么去呢?
SomeClass sc; if (someOtherClassObject instanceof SomeClass){ sc=(SomeClass) someOtherClassObject;
我想要的是
public void castDynamic (String strClassName){ //cast the classname referred by strClassName to SomeClass //if it is the instance of SomeClass }
编辑:以上是简化。 实际的代码就是这个
public void X(String className, RequestInterface request) { //My current code is this, I need to change so that "XRequest" //can be any class referred by "className", //and "request.getRequest" the object belonging to "className" class //I don't want static XRequest xvr, it should be fetched dynamically XRequest xvr; if (request.getRequest() instanceof XRequest){ xvr=(XRequest) request.getRequest(); client.setRequest(xvr); } }
另一个简单的改述:我使用request.getRequest()获取一个对象。 我不知道那个对象是什么。 所以我需要将它强制转换为提供的类字符串名称。 怎么做? 就这样。 – SQC 13分钟前
你想用它的名字实例化一个类?
首先,您需要创建一个Class>
对象:
Class> cls = Class.forName(strClassName);
然后实例化(注意,这可以抛出各种exception – 访问冲突, ClassNotFound
,没有参数的公共构造函数等)
Object instance = cls.newInstance();
然后你可以施展它:
return (SomeClass) instance;
请确保您了解以下两者之间的差异:
- 类名 (大约是文件名)
- 类对象 (本质上是类型信息)
- 类实例 (此类型的实际对象)
您还可以将cls
对象cls
转换为Class extends SomeClass>
如果你愿意,可以Class extends SomeClass>
。 但是,它并没有给你太多。 你可以内联它,:
return (SomeClass)(Class.forName(strClassName).newInstance());
哦,但你可以在实例化之前用cls
对象进行类型检查。 所以你只需要实现它,如果它满足你的API(实现你想要的接口)。
编辑:添加进一步的示例代码, 反思 。
例如:
if (cls.isInstance(request)) { // ... }
对于调用方法,您需要知道可以强制转换的接口,或者使用reflection ( cls
对象的getMethod
方法):
Method getRequest = cls.getMethod("getRequest"); getRequest.invoke(request);
您描述的问题没有明确定义。 转换是一种操作,它接受一个对象和一个Class,然后检查该对象是否是给定类的实例。
但是, cast(s) the classname referred by strClassName to SomeClass if it is the instance of SomeClass
那么你说你需要cast(s) the classname referred by strClassName to SomeClass if it is the instance of SomeClass
。 换句话说,你正在寻找适用于两个类(而不是类和对象)的东西。
所以,我们需要重申这个问题。 这里有三个可能的问题(+解决方案)我希望其中一个是您需要的
// Problem 1: check whether "object" can be casted to the class // whose name is "className" public void castDynamic(Object object, String className) { Class cls = Class.forName(className); cls.cast(object); } // Problem 2: check whether the class whose name is "className" // is a subclass of SomeClass (A is a subclass of B if A (transitively) // extends or implements B). public void castDynamic(String className) { Class cls = Class.forName(className); SomeClass.class.asSubclass(cls); } // Problem 3: check whether SomeClass is a sublcass the class // whose name is "className" public void castDynamic(String className) { Class cls = Class.forName(className); cls.asSubclass(SomeClass.class); }
完整详情: http : //docs.oracle.com/javase/6/docs/api/java/lang/Class.html#asSubclass(java.lang.Class )
你的意思是?
Class clazz = Class.forName(strClassName);