【发布时间】:2012-01-18 18:41:57
【问题描述】:
简单的问题,但我花了一个多小时来解决这个问题。我的代码如下。我需要使 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 分钟前
【问题讨论】:
-
也许你应该在你的问题中描述你想要的结果。基于字符串创建类的实例与动态转换无关。你想创建一个以字符串类名开头的已知类的实例,还是想创建一个以字符串类名开头的任何类的实例?
-
请查看更新后的问题(即使它有点令人困惑)。我正在创建的是一个接收类名的 api 调用,以及一个具有相同类名的对象。我需要将对象转换为方法中的类名(但请记住,我只有类名的字符串,而不是真正的类)。就这样。很简单。
-
正确的方法是将该方法放入
RequestInterface,然后您可以轻松调用它。除此之外,您需要使用 reflection 来检索要调用的方法。