3

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.

Jon C. Hammer
  • 392
  • 4
  • 8
  • 4
    One thing about using private inner classes is exactly that you don't want other people to use it. Why are you going this way? What's the issue at hand? – Jeroen Vannevel Nov 27 '13 at 00:56
  • Is there some method you want to invoke on your `B` instance? You could just use `toString()`, or you could use reflection to invoke an arbitrary method in B through it's instance. – Elliott Frisch Nov 27 '13 at 01:38
  • This is working correctly. I assume B implements some interface, since you have a reference to it. What are you trying to do that the interface reference is not sufficient? –  Nov 27 '13 at 01:45
  • 1
    Cast to an interface that B implements. – Hot Licks Nov 27 '13 at 02:37

1 Answers1

4

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?

Artem Tsikiridis
  • 682
  • 6
  • 11
  • In this particular case, there was a public interface that I could use. For some reason that never actually crossed my mind. Thank you! – Jon C. Hammer Dec 02 '13 at 05:37