CodeBlanks Logo Icon CodeBlanks

Class<?>

Learn class metadata with Class<?>.

The Class<?> object

Every type in Java has a Class<?> object; this object carries the type's information (fields, methods, constructors). Reflection starts here.

Three common paths: obj.getClass() gives the instance's class, String.class is the class literal, and Class.forName("java.lang.String") looks up the class object by name. All three return the same Class object; the choice depends on context.

Inspecting a Class

A Class object reveals a lot: getName returns the fully qualified name, getSimpleName the short name, getModifiers the access flags.

Example: c.getName() returns the full name like java.lang.String; c.getSimpleName() returns just String. These methods are used to inspect types at runtime; for example a framework that wants to log class names uses them directly.

Practice Print a class's fully qualified name

Get the Class object for String using Class.forName("java.lang.String"). Print the full name using getName() with System.out.println. Add throws ClassNotFoundException to main.

Starter code

Main.java
// Find the String class with Class.forName
// Get the full name with getName
// Add throws ClassNotFoundException and print

Sample solution

Main.java
public class ReflectionName {
    public static void main(String[] args) throws ClassNotFoundException {
        Class<?> c = Class.forName("java.lang.String");
        System.out.println(c.getName());
    }
}

Expected output

java.lang.String

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which method finds a class by its fully qualified name?

  • Class.forName Correct answer
  • getClass
  • getFields
  • getMethod

Explanation: Class.forName interprets a string as a class name.

2 Complete the Class.forName call

Question
Class<?> c = Class.____("java.lang.String");
Answer
Class<?> c = Class.forName("java.lang.String");

Explanation: forName interprets a string as a class name.

3 Match the ways to obtain a Class

Term Meaning
obj.getClass() Instance's class
String.class Class literal
Class.forName Find by name
getName Full name

All lessons in Advanced