View Javadoc

1   /*
2    * Copyright 2013 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.callbackparams.support;
17  
18  import java.util.regex.Pattern;
19  
20  /**
21   * Provides utility methods to help out wherever the framework shall
22   * act in different ways on different JDK versions.
23   * The only thing that is checked on the JDK version is whether it supports
24   * Java5-or-later (i.e. are annotations supported) or if only Java 1.4.x
25   * is supported.
26   *
27   * @author Henrik Kaipe
28   */
29  public class JdkVersion {
30  
31      private static final boolean annotationsAreSupported = new Object() {
32          public int hashCode() {
33              try {
34                  Class.forName("java.lang.annotation.Annotation");
35                  return 5;
36              } catch (Exception detection_of_JDK_version_1_4_or_earlier) {
37                  return 4;
38              }
39          }
40      }.hashCode() >= 5;
41      private static final Pattern packageName = annotationsAreSupported
42              ? Pattern.compile("^.*\\.") : null;
43  
44      /**
45       * @return true on Java-5 or later; false on Java 1.4.x
46       */
47      public static boolean supportsAnnotations() {
48          return annotationsAreSupported;
49      }
50  
51      /**
52       * On Java-5 or later the method tries to wrap a class with the same
53       * name as the argument class but from the "annotation" sub-package.
54       * On Java 1.4.x the method will simply wrap the argument class.
55       *
56       * @param c a class that is byte-code compatible with Java 1.4.x
57       */
58      public static ClassWrapper compatibleImplementationOf(Class c) {
59          if (supportsAnnotations()) {
60              try {
61                  c = Class.forName(packageName
62                          .matcher(c.getName()).replaceFirst("$0annotation."));
63              } catch (ClassNotFoundException ex) {
64                  throw ExceptionUtil.unchecked(ex);
65              }
66          }
67          return new ClassWrapper(c);
68      }
69  }