Getting Access To Private Fields in JAVA using Reflection:

Getting Access To Private Fields in JAVA using Reflection:



Private fields are... ehem, private, that means that they cannot (should not) be known, inspected or changed... now that inversion of control is common around us, what if a class is keeping a field private to protect it from 'abuse' but I want to access it just to abuse it softly (??? I should check my semantics when talking about code). What if I want Inversion of Control and I do not have an IOC Container? Ok, lets do it the hard (O_O ???) way.

For example, a Business Object is keeping a Data Object in private for it not to be directly used out of the Business Tier, but a Manager class wants to be made responsible for Business Tier's persistence. So the manager takes the Business Object, takes its DataObject, and persists it... but, it cannot! the Data Object was set to... private.

Ok, here is how to change that field access permissions during runtime:

Obtain a private field and play with it:   

        BusinessEntity businessEntity=... //The business object we are working with;
        DatabaseEntity databaseEntity;
        //_databaseEntity is the private field we want to play with.
        Field f = businessEntity.getClass().getDeclaredField("_databaseEntity"); 
        f.setAccessible(true);
        databaseEntity = (DatabaseEntity) f.get(businessEntity); //IllegalAccessException
        f.setAccessible(false);
        getDataTier.persist(databaseEntity);

Use it with caution, it is good it can be done, but may result in awful designs if not handled properly (you risk addicted).


   

Comments

Popular posts from this blog

Qt Signals and Slots, Connecting and Disconnecting

Vaadin 7: Detect Enter Key in a TextField

JAVA JPA WITH HIBERNATE AND H2 Tutorial