001// Copyright (c) 2001 Hursh Jain (http://www.mollypages.org) 002// The Molly framework is freely distributable under the terms of an 003// MIT-style license. For details, see the molly pages web site at: 004// http://www.mollypages.org/. Use, modify, have fun ! 005 006package fc.util; 007 008import java.net.*; 009import java.security.*; 010import java.lang.invoke.*; 011 012public final class ClassUtil 013{ 014static final String nl = fc.io.IOUtil.LINE_SEP; 015static final boolean dbg = false; 016 017/** 018Returns classloader information about the specified object 019*/ 020public static String getClassLoaderInfo(final Object obj) 021 { 022 Argcheck.notnull(obj, "specified obj param was null"); 023 return getClassLoaderInfo(obj.getClass()); 024 } 025 026/** 027Returns classloader information about the specified class. 028*/ 029public static String getClassLoaderInfo(final Class c) 030 { 031 Argcheck.notnull(c, "specified class param was null"); 032 033 ClassLoader cl = c.getClassLoader(); 034 035 StringBuffer buf = new StringBuffer(512); 036 037 buf.append("============== Classloader Information =================="); 038 buf.append(nl); 039 040 buf.append("System classloader = "); 041 buf.append(ClassLoader.getSystemClassLoader()); 042 buf.append(nl); 043 044 Thread t = Thread.currentThread(); 045 buf.append("Current thread = ").append(t); 046 buf.append(nl); 047 buf.append("Current thread context classloader = "); 048 buf.append(t.getContextClassLoader()); 049 buf.append(nl); 050 051 buf.append("Class loader hierarchy: "); 052 buf.append(nl); 053 buf.append("[").append(c); 054 buf.append("][package:"); 055 Package p = c.getPackage(); 056 buf.append(p != null ? p.getName() : "N/A"); 057 buf.append("]"); 058 059 buf.append("/ClassID:"); 060 buf.append(System.identityHashCode(cl)); 061 buf.append(" loaded by:"); 062 buf.append(nl); 063 064 String pad = " "; 065 while (cl != null) { 066 buf.append(pad); 067 buf.append(cl); 068 buf.append(nl); 069 cl = cl.getParent(); 070 pad += " "; 071 } 072 buf.append(pad + "null (bootstrap class loader)"); 073 buf.append(nl); 074 075 buf.append("========================================================="); 076 buf.append(nl); 077 return buf.toString(); 078 } 079 080/* SM is deprecated 081// to get the class name from a static method 082private static class CurrentClassGetter extends SecurityManager { 083 public String getClassName() { 084 return getClassContext()[2].getName(); 085 } 086 } 087*/ 088 089/** 090This method can be called from either a instance <b>or</b> a static method. 091 092Returns the class name in which the calling method was declared. 093<p> 094<b>Important note:</b> The returned class name is wherever the method is invoked from. For 095instance methods, it is the runtime virtual class. For static it is the class name where the method 096was declared (static methods are not virtual and bound at compile time). 097 098For example: 099<blockquote><pre><code> 100Class A 101 { 102 static void foo(...) { 103 System.out.print(ClassUtil.getClassName()); 104 } 105 } 106 107public class B extends A 108 { 109 } 110 111% java B 112will print: 113 A (NOT B) 114</code></pre></blockquote> 115*/ 116public static String getClassName() 117 { 118 //return new CurrentClassGetter().getClassName(); 119 120 return MethodHandles.lookup().lookupClass().getName(); 121 } 122 123 124/** 125Returns the fully qualified name of the class that contained the <code>main()</code> method used to 126invoke the application. 127 128<b>Note: </b> this method must be called from the same thread (the "main" thread) that started the 129application. Newly started threads that call this method will instead obtain the class name 130containing that thread's <code>run()</code> method. 131**/ 132public static String getMainClassName() 133 { 134 final StackTraceElement[] st = new Throwable().getStackTrace(); 135 //System.out.println("stack trace=" + Arrays.asList(st)); 136 final StackTraceElement mainElement = st[st.length-1]; 137 final String className = mainElement.getClassName(); 138 return className; 139 } 140 141/** 142Returns true is the specified class is a system/JDK class. This method should work, but given 143the vagaries of classes, classloaders, etc, there isn't any guarantee. 144 145@param c the object <i>or</i> {@link java.lang.Class} Class corresponding to that object 146*/ 147public static boolean isSystemClass(final Class c) 148 { 149 /* The param HAS to be Class, cannot be Object 150 151 isSystemClass(Object caller) 152 { 153 Class c = caller.getClass(); 154 ... 155 } 156 157 does NOT work - since 158 ==============ClassLoaderTest.java== 159 public static void main (String args[]) { 160 new ClassLoaderTest(); 161 } 162 public void printClassLoader(Object obj) { 163 System.out.println(obj); 164 Class c = obj.getClass(); 165 System.out.println(c); 166 System.out.println(c.getClassLoader()); 167 } 168 public ClassLoaderTest() { 169 printClassLoader(ClassLoaderTest.class); 170//====> class ClassLoaderTest => class java.lang.Class => null 171 172 printClassLoader(this); 173//====> ClassLoaderTest@4e25154f => class ClassLoaderTest => sun.misc.Launcher$AppClassLoader@15db974 174 } 175 ============== 176 */ 177 178 //all of the below return null. so this is true for java.* as well as javax.* at least. 179 //System.out.println(String.class.getClassLoader()); 180 //System.out.println(Object.class.getClassLoader()); 181 //System.out.println(java.sql.Connection.class.getClassLoader()); 182 //System.out.println(javax.sql.PooledConnection.class.getClassLoader()); 183 184 //boostrap classloaders are null (written in JDK C). This is an 185 //artifact of the JDK implementation, the spec doesn't mandate it. 186 187 if (c.getClassLoader() == null) { 188 return true; 189 } 190 191 return false; 192 } 193 194 195/* 196For regular files: 197 protection domain path: 198 /private/tmp/ 199 resource URL path to loaded class: 200 file:/private/tmp/test.class 201 202For jar files: 203 protection domain path: 204 /private/tmp/foo.jar 205 resource URL path to loaded class: 206 jar:file:/private/tmp/foo.jar!/test.class 207 208*/ 209 210 211/** 212Returns either the directory or jar file from which the specified class was loaded 213<p> 214This does not work for system/bootstrap classes and will return <code>null</code> for system classes. 215 216@param caller the {@link java.lang.Class} class to be looked up 217*/ 218public static String getLoadedFromPath(final Class caller) 219 { 220 //param has to be class, cannot be Object, static compile time binding 221 222 final ProtectionDomain pd = caller.getProtectionDomain(); 223 if (pd == null) { //should not be null for system/boostrap classes but just to be sure 224 if (dbg) System.out.println("ProtectionDomain for " + caller + " was null"); 225 return null; 226 } 227 228 final CodeSource cs = pd.getCodeSource(); 229 if (cs == null) { //is definitely null for system/boostrap classes 230 if (dbg) System.out.println("CodeSource for " + caller + " was null"); 231 return null; 232 } 233 234 final String path = cs.getLocation().getPath(); 235 return path; 236 } 237 238/** 239Returns the right most <b>parent</b> directory from which the actual class was loaded. This is the leaf directory where 240the actual class is located. 241<p> 242For classes loaded from other sources (jar, etc), the return value will be null. 243<p> 244This also does not work for system/bootstrap classes (they are typically loaded from jars) either (those will 245return null also) 246<p> 247@param caller the {@link java.lang.Class} class to be looked up 248*/ 249public static String getParentDir(final Class caller) 250 { 251 final String classname = StringUtil.fileName(caller.getName().replace('.', '/')) + ".class"; 252 final URL location = caller.getResource(classname); 253 254 if (location == null) return null; 255 if (dbg) System.out.println("protocol: " + location.getProtocol()); 256 257 String protocol = location.getProtocol(); 258 if (protocol == null) return null; 259 260 if (protocol.equalsIgnoreCase("file")) { 261 return StringUtil.dirName(location.getFile()); 262 } 263 264 return null; 265 } 266 267 268/** 269Returns the <b>parent</b> directory from which the actual class was loaded. This is the leaf directory where 270the actual class is located. 271<p> 272For classes loaded from other sources (jar, etc), a URL will be returned. For jar URL's, the 273URL.getProtocol() method returns "jar", so that can be useful for further processing as needed. 274<p> 275@param caller the {@link java.lang.Class} class to be looked up 276*/ 277public static URL getParentDirAsURL(final Class caller) 278 { 279 final String classname = StringUtil.fileName(caller.getName().replace('.', '/')) + ".class"; 280 final URL location = caller.getResource(classname); 281 final String parent = StringUtil.dirName(location.toString()); 282 if (dbg) System.out.println(parent); 283 URL url = null; 284 try { 285 url = new URL(parent); 286 } 287 catch (Exception e) { 288 System.err.println(fc.io.IOUtil.throwableToString(e)); 289 } 290 return url; 291 } 292 293public static void main (String args[]) 294 { 295 System.out.println(ClassUtil.getClassLoaderInfo(ClassUtil.class)); 296 297 Class obj = new Object().getClass(); 298 299 System.out.println(ClassUtil.getClassLoaderInfo(obj)); 300 System.out.println("getClassName(): " + getClassName()); 301 System.out.println("getMainClassName(): " + getMainClassName()); 302 303 System.out.println(); 304 305 System.out.println("-------- these should return null --(system classes) ------"); 306 307 test(obj); 308 309 System.out.println("-------- these should return a value (either jar or directory) ------"); 310 test (ClassUtil.class); 311 312 System.out.println("-------- these should return a value (either jar or directory) ------"); 313 test(new org.json.JSONObject().getClass()); 314 } 315 316private static void test (Class obj) 317 { 318 System.out.println(obj); 319 System.out.println("isSystemClass: " + isSystemClass(obj)); 320 System.out.println("getLoadedFromPath: " + getLoadedFromPath(obj)); 321 System.out.println("getParentDir: " + getParentDir(obj)); 322 System.out.println("getParentDirAsURL: " + getParentDirAsURL(obj)); 323 System.out.println(); 324 } 325} 326 327 328