1 package com.puppycrawl.tools.checkstyle.checks; 20 21 import java.util.Set ; 22 import java.util.Iterator ; 23 24 32 public class ClassResolver 33 { 34 35 private final String mPkg; 36 37 private final Set mImports; 38 39 private final ClassLoader mLoader; 40 41 48 public ClassResolver(ClassLoader aLoader, String aPkg, Set aImports) 49 { 50 mLoader = aLoader; 51 mPkg = aPkg; 52 mImports = aImports; 53 mImports.add("java.lang.*"); 54 } 55 56 68 public Class resolve(String aName, String aCurrentClass) 69 throws ClassNotFoundException 70 { 71 Class clazz = resolveQualifiedName(aName); 73 if (clazz != null) { 74 return clazz; 75 } 76 77 Iterator it = mImports.iterator(); 79 while (it.hasNext()) { 80 final String imp = (String ) it.next(); 81 if (imp.endsWith("." + aName)) { 86 clazz = resolveQualifiedName(imp); 87 if (clazz != null) { 88 return clazz; 89 } 90 91 } 92 } 93 94 if (!"".equals(mPkg)) { 96 clazz = resolveQualifiedName(mPkg + "." + aName); 97 if (clazz != null) { 98 return clazz; 99 } 100 } 101 102 if (!"".equals(aCurrentClass)) { 104 final String innerClass = (!"".equals(mPkg) ? (mPkg + ".") : "") 105 + aCurrentClass + "$" + aName; 106 if (isLoadable(innerClass)) { 107 return safeLoad(innerClass); 108 } 109 } 110 111 it = mImports.iterator(); 113 while (it.hasNext()) { 114 final String imp = (String ) it.next(); 115 if (imp.endsWith(".*")) { 116 final String fqn = imp.substring(0, imp.lastIndexOf('.') + 1) 117 + aName; 118 clazz = resolveQualifiedName(fqn); 119 if (clazz != null) { 120 return clazz; 121 } 122 } 123 } 124 125 return safeLoad(aName); 128 } 129 130 134 public boolean isLoadable(String aName) 135 { 136 try { 137 safeLoad(aName); 138 return true; 139 } 140 catch (final ClassNotFoundException e) { 141 return false; 142 } 143 } 144 145 152 public Class safeLoad(String aName) 153 throws ClassNotFoundException 154 { 155 return Class.forName(aName, false, mLoader); 159 } 160 161 166 private Class resolveQualifiedName(final String aName) 167 { 168 try { 169 if (isLoadable(aName)) { 170 return safeLoad(aName); 171 } 172 final int dot = aName.lastIndexOf("."); 174 if (dot != -1) { 175 final String innerName = 176 aName.substring(0, dot) + "$" + aName.substring(dot + 1); 177 if (isLoadable(innerName)) { 178 return safeLoad(innerName); 179 } 180 } 181 } 182 catch (final ClassNotFoundException ex) { 183 throw new RuntimeException (ex); 186 } 187 188 return null; 189 } 190 } 191 | Popular Tags |