How do I pass a class as a parameter in Java?
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:
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:
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:
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:
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:
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.
Was this article helpful?