View Javadoc
1   /**
2    *    Copyright 2006-2016 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.mybatis.generator.api.dom.java;
17  
18  public class JavaDomUtils {
19      /**
20       * Calculates type names for writing into generated Java.  We try to
21       * use short names wherever possible.  If the type requires an import,
22       * but has not been imported, then we need to use the fully qualified
23       * type name.
24       * 
25       * @param compilationUnit the compilation unit being written
26       * @param fqjt the type in question
27       */
28      public static String calculateTypeName(CompilationUnit compilationUnit, FullyQualifiedJavaType fqjt) {
29          if(compilationUnit == null
30                  || typeDoesNotRequireImport(fqjt)
31                  || typeIsInSamePackage(compilationUnit, fqjt) 
32                  || typeIsAlreadyImported(compilationUnit, fqjt)) {
33              return fqjt.getShortName();
34          } else {
35              return fqjt.getFullyQualifiedName();
36          }
37      }
38      
39      private static boolean typeDoesNotRequireImport(FullyQualifiedJavaType fullyQualifiedJavaType) {
40          return fullyQualifiedJavaType.isPrimitive()
41                  || !fullyQualifiedJavaType.isExplicitlyImported();
42      }
43      
44      private static boolean typeIsInSamePackage(CompilationUnit compilationUnit, FullyQualifiedJavaType fullyQualifiedJavaType) {
45          return fullyQualifiedJavaType.getPackageName().equals(compilationUnit.getType().getPackageName());
46      }
47      
48      private static boolean typeIsAlreadyImported(CompilationUnit compilationUnit, FullyQualifiedJavaType fullyQualifiedJavaType) {
49          FullyQualifiedJavaType nonGenericType = new FullyQualifiedJavaType(fullyQualifiedJavaType.getFullyQualifiedNameWithoutTypeParameters());
50          return compilationUnit.getImportedTypes().contains(nonGenericType);
51      }
52  }