Adam Connor
Posts: 12
Nickname: adamconnor
Registered: Jan, 2004
|
|
Re: instanceExists() ...
|
Posted: Jan 22, 2004 5:54 PM
|
|
I think this is a tricky question to answer. Assuming that finding out if the class has been loaded is good enough, the method you want is findLoadedClass(String name) in ClassLoader; it will return null if the class has not been loaded.
However, it is a protected final method, so you can't call it directly. The following program outlines one approach for accessing it:
public class TestClassIsLoaded { public static void main(String[] args) throws Exception { TestClassIsLoaded test = new TestClassIsLoaded(); System.out.println("BigDecimal loaded? " + test.isLoaded("java.math.BigDecimal") ); System.out.println("String loaded? " + test.isLoaded("java.lang.String")); BigDecimal bd = new BigDecimal(0); System.out.println("BigDecimal loaded? " + test.isLoaded("java.math.BigDecimal") ); }
public boolean isLoaded(String className) throws IllegalAccessException, InvocationTargetException {
ClassLoader loader = TestClassIsLoaded.class.getClassLoader(); Class lc = loader.getClass(); while( lc != null ){ try { Method m = lc.getDeclaredMethod( "findLoadedClass", new Class[]{String.class} ); // next line requires "suppressAccessChecks" permission if security is on m.setAccessible(true); Object result = m.invoke(loader, new Object[]{className}); return result != null; } catch (NoSuchMethodException e) { lc = lc.getSuperclass(); continue; } } throw new IllegalStateException("Never found \"findLoadedClass\"."); } }
If you are running with the SecurityManager turned on, you will need sufficient permissions to perform these operations.
|
|