Thursday, 21 July 2022

How to check whether a class is loaded or not in Java?

Using ‘findLoadedClass’ method of ClassLoader, we can check whether a class is loaded or not.

 

Signature

protected final Class<?> findLoadedClass(String name)

 

Since ‘findLoadedClass’ is a protected method, we can access this method either by extending the class ClassLoader or via reflections.

 

Below snippet check via reflection

private static boolean isClassLoaded(final String classBinaryName) throws NoSuchMethodException, SecurityException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException {

	final Method method = ClassLoader.class.getDeclaredMethod("findLoadedClass", new Class[] { String.class });
	method.setAccessible(true);
	final ClassLoader classLoader = ClassLoader.getSystemClassLoader();
	
	final Object clazz = method.invoke(classLoader, classBinaryName);
	
	return clazz != null;
}

Find the below working application.

 


A.java
package com.sample.app.dto;

public class A {

	static {
		System.out.println(A.class + " is loaded");
	}
	
	public A() {
		System.out.println(A.class + " constructor is loaded");
	}

}

ClassLoaderCheck.java

package com.sample.app.reflections;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.sample.app.dto.A;

public class ClassLoaderCheck {

	private static boolean isClassLoaded(final String classBinaryName) throws NoSuchMethodException, SecurityException,
			IllegalAccessException, IllegalArgumentException, InvocationTargetException {

		final Method method = ClassLoader.class.getDeclaredMethod("findLoadedClass", new Class[] { String.class });
		method.setAccessible(true);
		final ClassLoader classLoader = ClassLoader.getSystemClassLoader();

		final Object clazz = method.invoke(classLoader, classBinaryName);

		return clazz != null;
	}

	public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException,
			InvocationTargetException, NoSuchMethodException, SecurityException {

		System.out.println("Is com.sample.app.dto.A loaded " + isClassLoaded("com.sample.app.dto.A"));

		System.out.println("\nInstantiate A, to get it loaded by the class loader");
		A a = new A();

		System.out.println("\nIs com.sample.app.dto.A loaded " + isClassLoaded("com.sample.app.dto.A"));
	}

}

Output

Is com.sample.app.dto.A loaded false

Instantiate A, to get it loaded by the class loader
class com.sample.app.dto.A is loaded
class com.sample.app.dto.A constructor is loaded

Is com.sample.app.dto.A loaded true

 

 

You may like

Interview Questions

Closeable vs AutoCloseable in Java

What is the behaviour of static final method in Java?

How to check two double values for equality?

Why to do explicit type casting from double to float conversion?

When is a class or interface is initialized or loaded in Java?

How to check two float values equality?

No comments:

Post a Comment