Explain Codes LogoExplain Codes Logo

How to use Class<T> in Java?

java
generics
reflection
type-safety
Nikita BarsukovbyNikita Barsukov·Dec 12, 2024
TLDR

Here's how to use Class<T>, quick and easy:

// Grabbing Class object for String (easy as grabbing popcorn!) Class<String> strClass = String.class; // Conjuring up new String instance (abracadabra!) String strInstance = strClass.newInstance(); // Fetching simple class name for a neat printout String simpleName = strClass.getSimpleName(); // Output: 'String', as plain as day System.out.println(simpleName);

Thrive with Class<T> to tap into metadata and construct new objects. You can bag the Class object with String.class, sprout new instances via newInstance(), and get the class name with getSimpleName().

Delving into Class<T> in Java

Mastering generics with Class<T>

Class<T> provides a smart way to work with generics, acting as a type-safe container for any class type T. It unleashes benefits of:

  • Type safety: You can specify the exact type of objects you'll be handling.
  • No casting: You no longer need to cast explicitly when creating objects!

Playing with type parameter in generic methods

Generic methods offer their own type parameters. Like a new toy:

public static <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException { return clazz.newInstance(); }

The <T> before the return type declutters your code by replacing cumbersome manual type handling.

Subtype magic with wildcards

The wildcards (?) hitch with Class<T> gives birth to magic of working with subtypes:

public void processClass(Class<? extends Number> cls) { // Code to process classes that are Johnny's little brothers and sisters of Number }

Reflective powers of Class<T>

Class<T> is your friendly guide in the jungle of reflection. Dig into metadata, create objects on the go:

Class<?> dynamicClass = Class.forName("java.util.ArrayList"); Object arrayList = dynamicClass.newInstance();

Using Class<T> as a type token

You can use Class<T> as a type token, providing both runtime and compile-time awareness of tracks:

public static <T> void printClassInfo(Class<T> clazz) { System.out.println(clazz.getTypeName()); }

Revealing reflection capabilities

Reflection lets you inspect and alter code dynamic, and Class<T> is a key player. Ride along to:

  • Access constructors, methods, and fields.
  • Create objects from what seems like thin air!

Dig these ways of reducing casting with Class<T>:

public <T> T makeNew(Class<T> clazz) { // No newtype ({})! eliminates the casting roundabout return clazz.newInstance(); }

Crafting services with Class<T>

Say hi to service loaders or factory patterns with Class<T>:

ServiceLoader<MyInterface> loader = ServiceLoader.load(MyInterface.class);

"Oops" moments with Class<T>

Beware of little trip-ups in Class<T> country:

  • ClassCastException: They happen if you mess up with casting, but generics can be your safety hat.
  • newInstance won a free trip to deprecated land in Java 9