title: Compiling in Java 7 a method that uses Java 8 types
body: <p>I need to write code to handle dates. We are slowly transitioning from Java 7 to Java 8, so my library code <strong>has to work</strong> with both. For this reason it must be compiled Java 7.</p>
  
  <p>However, projects already migrated to Java 8 started using JSR-310 types.</p>
  
  <p>Consider the following statements</p>
  
  <pre><code>if (obj instanceof Date){
      //Serialize using SimpleDateFormat
  } else if (obj instanceof org.joda.time.LocalDateTime){
      //Serialize using Joda
  } else if (obj instanceof java.time.LocalDateTime){
      //Serialize using JSR 310
  }
  </code></pre>
  
  <p>I am not using Lambdas or other language stuff introduced by Java 8. I am using a Java 8 compiler anyway. What I want is to create Java 7 compatible code (so no <code>UnsupportedClassVersionError</code>) that breaks when the third if branch is hit in Java 7 (<code>NoClassDefFoundError</code>).</p>
  
  <p>Currently the above code does not compile at all if I use a Java 8 javac compiler set for Java 7 target.</p>
  
  <p>I run Ant in a Java 8 environment</p>
  
  <pre><code>&lt;javac includeantruntime="false" srcdir="src" destdir="build/compiled" target="1.7" source="1.7"
  </code></pre>
  
  <p>But if I use <code>import java.time.LocalDateTime</code> as a <em>trick</em> it won't compile.
  I imagined that a Java 8 compiler targeting to Java 7 was not so smart to see that while the <code>LocalDateTime</code> class <strong>is available</strong> in Java 8 classpath, it is not in Java 7.</p>
  
  <p>What I don't want is to use reflection (<code>if (obj.getClass().getCanonicalName().equals("java.time.LocalDateTime")</code> and other reflection-based stuff) and I prefer not to add a dependency to <a href="http://mvnrepository.com/artifact/org.threeten/threetenbp" rel="nofollow noreferrer"><em>ThreeTen-Backport</em></a> as JSR-310 types are <strong>not</strong> being used in Java 7 projects and I prefer to exclude threeten from Java 8 projects without messing with the Ivy dependencies file.</p>
  
  <p>Any smart idea? I already have a solution (Service Provider Interface with separate Jars) but I want to keep it as last resort.</p>