In Java, whenever an inner class instance is created, it is associated with an instance of an outer class. Out of curiosity, is it possible to associate the inner class with another instance of an outer class instead?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
You should be able to, using reflection.
Just get all fields of the inner class (
getClass().getDeclaredFields()
)and see which field holds the parent, then change it (usingfield.set(innerInstance, newParent)
. Before that you should make the field accessible -setAccessible(true)
)Since the field appears to be
final
, you may take a look at this article to see how to circumvent that.That said, you shouldn't need to do this at all - it would be a double ugly hack for no actual gain.
Yes, this is possible, although it sounds like a really bad idea to me. The idea is to set the otherwise
final
pointer to the outer instance using reflection (which is not guaranteed to succeed).The crucial part here is
outerThis.setAccessible(true);
-- a SecurityManager could enforce a policy that prohibits this from succeeding.If you are speaking about instantiation time, it's possible using the following syntax:
However, it's not possible (without
setAccessible(true)
) to associate the existing instance of inner class with the other instance of outer class, because the field pointing to the enclosing instance isfinal
: