KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > JSX > PackageRefactor


1 package JSX;
2 import java.util.Map JavaDoc;
3 import java.util.List JavaDoc;
4 import java.util.Iterator JavaDoc;
5 public class PackageRefactor implements Refactor {
6     Map JavaDoc map;
7     public PackageRefactor(Map JavaDoc map) { //takes a HashMap, HashTable etc
8
this.map = map;
9             // check for correct types:
10
// String, String
11
// String, List <---- for safe auto-discovery
12
//check that there is no merging (possible clash) "not many:1"
13
//Alt: load up from an array (of String[][]? or two String[]?)
14
}
15     public String JavaDoc mapClassname(String JavaDoc packageQualifiedClassname) {
16         String JavaDoc initialPackage = packageQualifiedClassname.substring(0, packageQualifiedClassname.lastIndexOf('.')); // extract package name
17
String JavaDoc initialClassname = packageQualifiedClassname.substring(packageQualifiedClassname.lastIndexOf('.')+1);
18
19         Object JavaDoc packageOrList = map.get(initialPackage); // map to new one
20
if (packageOrList==null)
21             return packageQualifiedClassname; // leave as is
22
else if (packageOrList instanceof String JavaDoc)
23             return ((String JavaDoc) packageOrList)+"."+initialClassname; // create new one
24
else if (packageOrList instanceof List JavaDoc) { //search through list
25
boolean found = false;
26             String JavaDoc newFullName = null;
27             for (Iterator JavaDoc i = ((List JavaDoc)packageOrList).iterator(); i.hasNext(); ) {
28                 newFullName = ((String JavaDoc)i.next())+"."+initialClassname;
29                 Class JavaDoc clazz;
30                 try {
31                     clazz=Thread.currentThread().getContextClassLoader().loadClass(newFullName); // we could factor this out
32
found = true;
33                     break; // success! Now end the search
34
} catch (ClassNotFoundException JavaDoc ignored) {}
35             }
36             if (found)
37                 return newFullName;
38             else
39                 return null; // auto-discovery failed - throw ClassNotFoundException?
40
}
41         else
42             throw new Error JavaDoc("Value corresponding to "+ initialPackage +" is "+ packageOrList.getClass() + " but should be List, String or null");
43     }
44 }
45
Free Books   Free Magazines  
Popular Tags