How to cast to a private inner class when type inf

2019-08-14 22:43发布

问题:

I have a situation similar to the following:

// 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;

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

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.

回答1:

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):

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?