title: Synchronization on an object retrieved via reflection
body: <p>I'm hooking into a method via the <a href="http://forum.xda-developers.com/xposed/xposed-installer-versions-changelog-t2714053" rel="nofollow noreferrer">Xposed framework for Android</a>. This effectively allows me to inject my own code into another Android app at runtime and have it run just as if the target app was built with it. Fun stuff. While this is <em>how</em> I'm injecting the code, my question should be independent of Xposed as it's using an extension of the standard Java reflection utilities to retrieve the class references I need.</p>
  
  <pre><code>Class targetClass = XposedHelpers.findClass("fullClassName", targetAppClassLoader);
  Object timerField = XposedHelpers.getStaticObjectField(targetClass, "targetFieldName");
  // This /should/ synchronize with the actual static field not our local representation of it
  synchronized (timerField) {
      // Do stuff
  }
  </code></pre>
  
  <p>In the above snippet I'm retrieving a static object field in a class via reflection. Internally, the target app uses <code>synchronized</code> blocks on this field. I need to operate in a similar synchronous manner so I do the same in my own code (<a href="https://github.com/kmark/XHangouts/blob/v1.6/app/src/main/java/com/versobit/kmark/xhangouts/XHangouts.java#L528" rel="nofollow noreferrer">link to full code</a>).</p>
  
  <p>Since <a href="https://stackoverflow.com/a/40523/238374">Java objects are sorta passed by reference</a> I should be retrieving a local reference to the static object in the target app. <strong>But do Java <code>synchronized</code> blocks work on reflected objects? And do they work together with non-reflected pre-existing <code>synchronized</code> blocks?</strong></p>
  
  <p>For reference, here is the code for <a href="https://github.com/rovo89/XposedBridge/blob/afcc3e1e788ea44bfd00245a24b5dfe6c86aa3d0/src/de/robv/android/xposed/XposedHelpers.java#L46" rel="nofollow noreferrer"><code>findClass</code></a> and <a href="https://github.com/rovo89/XposedBridge/blob/afcc3e1e788ea44bfd00245a24b5dfe6c86aa3d0/src/de/robv/android/xposed/XposedHelpers.java#L832" rel="nofollow noreferrer"><code>getStaticObjectField</code></a>. The former essentially returns a returns a <code>Class&lt;?&gt;</code> from <code>org.external.org.apache.commons.lang3.ClassUtils</code> and the latter (essentially) calls <code>getDeclaredField</code> on the <code>Class&lt;?&gt;</code> parameter, sets the <code>Field</code> to accessible, and returns the result of <code>get(null)</code> on the <code>Field</code>.</p>