这是一个简单的问题,但我已经花了一个多小时来解决。我的代码如下所示。我需要使SomeClass sc成为动态的。因此,您可以在函数中传递类名作为字符串,并在静态someClass的位置使用该类。如何处理?
SomeClass sc;
if (someOtherClassObject instanceof SomeClass){
sc=(SomeClass) someOtherClassObject;
What I want is
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分钟前