当类型信息不可用时,如何转换为私有内部类? [英] How to cast to a private inner class when type information is unavailable?

查看:44
本文介绍了当类型信息不可用时,如何转换为私有内部类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到类似以下情况:

// In some library code
public class A
{
    private class B
    {
        Object value;
    }
}

// In my code
Object o;

// o is initialized to an instance of B somehow
// ...

B bInstance = (B) o;

如果无法访问B类型,我该如何强制将对象转换为类型B??

How would I go about casting an Object to type B given that the type of B is inaccessible?

为了更详细地说明,A不是我的代码库的一部分.它是图书馆的一部分.我可以访问我知道的类型B的对象,但是由于类型信息不可见,所以无法进行转换(例如,在IDE中).这是一个编译错误.情况是非常严格的.我认为可能可以通过反射来实现,但是恐怕我没有太多使用该特定范式的经验.有没有办法解决?我感谢社区提供的任何意见.

To explain in more detail, A is not part of my code base. It's part of a library. I have access to an object that I know is of type B, but I can't cast it (in an IDE, for example) because the type information is not visible. It's a compilation error. The situation is very restrictive. I think it might be possible to achieve this using reflection, but I'm afraid I don't have a lot of experience using that particular paradigm. Is there any way around this? I appreciate any input the community would offer.

推荐答案

也许您应该访问一个接口?还是也无法理解?

Maybe there is an interface you should be accesing instead? Or is it inaccesible too?

我不知道您是否需要以下内容,但这也许可以帮助您找到解决方法(因为您要求使用反射):

I don't know whether the following is what you need, but maybe this can help you find a workaround (since you asked for uses of reflection):

既然您以某种方式拥有B实例,就应该尝试:

Since you somehow have your B instance you should try:

Class<?> innerClass = o.getClass();

然后,如果可能的话,尝试使用如下反射来获得所需的内容:

And then if possible, try to get what you need by using reflection like this:

Field allFields[] = innerClass.getDeclaredFields();    
Constructor<?> constructors[] = innerClass.getDeclaredConstructors();
Method allMethods[] = innerClass.getDeclaredMethods();

constructor.setAccessible(true);  sets the constructor accessible.

您可以自己实例化该实例,还是使用以某种方式返回的实例很重要?

Can you instantiate the instance yourself or is it important to use the one somehow returned?

这篇关于当类型信息不可用时,如何转换为私有内部类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆