Note that there are some explanatory texts on larger screens.

plurals
  1. POAccessing fields from a proxied object
    text
    copied!<p>I've run into an interesting problem while developing an ORM framework for Android. I'm using a library called <a href="http://code.google.com/p/dexmaker/" rel="noreferrer">dexmaker</a> for bytecode manipulation, which enables me to create proxies for persistent objects in order to implement lazy loading.</p> <p>The proxied instance has an associated <code>InvocationHandler</code> such that when a method is called on the proxy, the <code>invoke</code> method is called on the <code>InvocationHandler</code>, which then calls the proxied object's respective method assuming it's been lazily loaded. Nothing too surprising -- it's just like Java's <a href="http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/reflect/Proxy.html" rel="noreferrer">Proxy</a> class but allows me to proxy actual classes instead of interfaces (see dexmaker's <a href="http://dexmaker.googlecode.com/git/javadoc/com/google/dexmaker/stock/ProxyBuilder.html" rel="noreferrer">ProxyBuilder</a>).</p> <p>The part that's become problematic is that I also use reflection to retrieve field values from persistent objects and -- now that I've introduced lazy loading -- proxies. Here is what I'm currently doing:</p> <pre><code>for (Field f : getPersistentFields(model.getClass()) { ... Object val = f.get(model); // model is either a persistent object or a proxy for one mapField(f, val, map); } </code></pre> <p>This of course works for regular model instances, but for proxied instances, <code>f.get(model)</code> is not retrieving the proxied object's field value. Instead, it's returning the default value assigned in the class's constructor. The access on the proxy's field is not being intercepted obviously.</p> <p><strong>My question is this:</strong> is there any way I can intercept an access on a proxy's member variable made through reflection? If not, how can I retrieve the value of a proxy's field in a "reflection-like" way?</p> <p><strong>One possible workaround</strong> I'm thinking of would be to retrieve and then invoke the field's getter method using reflection, but I'm wondering if there's a more direct solution. This workaround, if it actually <em>works</em>, would require the object to have a getter method for all persistent fields -- a requirement that should typically be followed from an OO-design point of view but also forces more work onto the user of the framework.</p> <p>I'm open to any ideas.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload