¿Cómo transmitir a una clase interna privada cuando la información de tipo no está disponible?
Frecuentes
Visto 3,969 veces
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 no 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 Respuestas
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?
respondido 27 nov., 13:01
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. Martillo
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas java class reflection private or haz tu propia pregunta.
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
Is there some method you want to invoke on your
B
instance? You could just usetoString()
, or you could use reflection to invoke an arbitrary method in B through it's instance. - Elliott FrischThis 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? - user439793
Cast to an interface that B implements. - Hot Licks