Explain Codes LogoExplain Codes Logo

How do I pass a class as a parameter in Java?

java
reflection
type-safety
error-handling
Alex KataevbyAlex Kataev·Feb 13, 2025
TLDR

To pass a Class object to a method, use the MyClass.class notation where the method parameter expects a Class<?>. Major usage can be found in reflection or generics. Check this out:

public <T> void handleClass(Class<T> classType) { // Class incoming! // Magic happening with classType } handleClass(String.class); // String.class in action!

If dynamic object creation is what you are after, Class.forName("MyClass") can be used to get the Class object, and of course, don't forget your friendly neighbourhood villain ClassNotFoundException, always be ready for him.

Working with the Class<T> parameter

Type parameter constraints

Enforcing type safety by bounding type parameters secures your code from unwanted runtime parties:

public static <T extends Number> void numberHandler(Class<T> numberClass) { // No Strings attached ;) // Safe operations with numberClass }

What we've done here is made sure our method only hugs Number types. It's the VIP only approach to accepting classes as parameters.

Reflection game with Class objects

Reflection turns your code into a mystical ninja, able to inspect and manipulate classes and objects at runtime:

Class<?> ninjaClass = Class.forName("com.example.MyClass"); Method aSecretMethod = ninjaClass.getMethod("myMethod", String.class); aSecretMethod.invoke(ninjaClass.newInstance(), "hiddenParameter"); // Even ninjas need some "reflection" ;)

In this snippet, getMethod retrieves a Method object, which is then invoked on an instance of com.example.MyClass triumphantly created on-the-fly.

Creating instances 'cause we can!

You can create instances using the provided Class object while preserving the all-important type safety:

public <T> T spawnInstance(Class<T> classType) throws InstantiationException, IllegalAccessException { // Type safety first, always! return classType.newInstance(); // Create all things, one by one. Beware! Deprecated since Java 9 }

This ensures we have a treasure chest full of instances, neatly wrapped in their respective types.

Reflection: powerful but handle with care

Although Reflection is like a magic wand that can manipulate anything at runtime, avoid using it as your go-to weapon. Think alternatives like Factory Methods or Service Loaders. Balance is key.

Error handling: your code's best friend

Because even ninjas stumble sometimes, error handling is crucial:

try { Class<?> aClass = Class.forName("com.example.SomeClassThatMightNotExist"); // I have a bad feeling about this... } catch (ClassNotFoundException classNotFoundHeyItHappensRight) { // Deal with the reality of class not found }

Just as ninja preparations include handling all possible scenarios, consider all possible exceptions like IllegalAccessException, IllegalArgumentException, and InvocationTargetException while performing reflection operations in try-catch.