Java Class Metadata: Names, Modifiers, Hierarchy and Generics
Java class metadata is the information a Class object holds about a type: its names, its kind (class, interface, enum, record), its modifiers, its superclass and interfaces, its generic type arguments, its nested types, and the package and module it lives in.
Frameworks read this metadata constantly. A dependency injection container checks which interfaces a class implements, a JSON library reads generic types such as List<String>, and a test runner skips abstract classes. In Java Reflection API you used Class to reach fields, methods and constructors. This lesson covers the rest of what Class can tell you and ends with a small javap-style class inspector.
Java Class Names: getName, getSimpleName and getCanonicalName
A class has several names, and each method returns a different one. The difference shows up for nested classes, arrays, local classes and anonymous classes.
import java.util.Map;
public class ClassNames {
static class Nested { }
public static void main(String[] args) {
Runnable anonymous = new Runnable() {
public void run() { }
};
class LocalHelper { }
Class<?>[] types = {String.class, Nested.class, Map.Entry.class, int[][].class,
LocalHelper.class, anonymous.getClass(), int.class};
System.out.printf("%-24s %-14s %-20s %s%n", "getName", "getSimpleName", "getCanonicalName", "getPackageName");
for (Class<?> type : types) {
System.out.printf("%-24s %-14s %-20s \"%s\"%n", type.getName(), "\"" + type.getSimpleName() + "\"",
type.getCanonicalName(), type.getPackageName());
}
}
}
Output:
getName getSimpleName getCanonicalName getPackageName
java.lang.String "String" java.lang.String "java.lang"
ClassNames$Nested "Nested" ClassNames.Nested ""
java.util.Map$Entry "Entry" java.util.Map.Entry "java.util"
[[I "int[][]" int[][] "java.lang"
ClassNames$1LocalHelper "LocalHelper" null ""
ClassNames$1 "" null ""
int "int" int "java.lang"
How it works:
| Method | Returns | Use it for |
|---|---|---|
getName() | The binary name used by the JVM, with $ for nested types and [I style for arrays | Class.forName, logs, unique keys |
getSimpleName() | The name as written in source, empty for anonymous classes | Display text |
getCanonicalName() | The name you would write in an import, or null if there is none | Generating source code |
getTypeName() | A readable name, with int[][] style for arrays | Messages and tooling |
getPackageName() | The package, or "" for the default package | Grouping and filtering |
Map.Entryis nested, so its binary name uses$(java.util.Map$Entry) while its canonical name uses.(java.util.Map.Entry).- Local and anonymous classes have no canonical name, because you cannot refer to them from outside the method. Their binary names get compiler-generated numbers such as
ClassNames$1. - Only
getName()output can be passed back toClass.forName. Primitives such asinthave a name but no class file, soClass.forName("int")fails.
Java Class Metadata: Kind of Type and Modifiers
A Class object can represent a class, interface, enum, record, annotation, array or primitive. A family of isX() methods tells them apart, and getModifiers() returns the declaration's modifiers as an int bit mask.
import java.lang.reflect.Modifier;
import java.util.List;
interface Shape { }
enum Level { BEGINNER, ADVANCED }
record Point(int x, int y) { }
@interface Marker { }
abstract class Base { }
sealed interface Payment permits Card, Upi { }
final class Card implements Payment { }
non-sealed class Upi implements Payment { }
public class KindOfType {
static String kind(Class<?> type) {
if (type.isAnnotation()) return "annotation"; // check first: annotations are interfaces too
if (type.isInterface()) return "interface";
if (type.isEnum()) return "enum";
if (type.isRecord()) return "record";
if (type.isArray()) return "array";
if (type.isPrimitive()) return "primitive";
return "class";
}
public static void main(String[] args) {
Class<?>[] types = {Shape.class, Level.class, Point.class, Marker.class, Base.class,
Payment.class, Card.class, Upi.class, String[].class, double.class, List.class};
for (Class<?> type : types) {
System.out.printf("%-9s %-10s sealed=%-5s modifiers=[%s]%n", type.getSimpleName(), kind(type),
type.isSealed(), Modifier.toString(type.getModifiers()));
}
}
}
Output:
Shape interface sealed=false modifiers=[abstract interface]
Level enum sealed=false modifiers=[final]
Point record sealed=false modifiers=[final]
Marker annotation sealed=false modifiers=[abstract interface]
Base class sealed=false modifiers=[abstract]
Payment interface sealed=true modifiers=[abstract interface]
Card class sealed=false modifiers=[final]
Upi class sealed=false modifiers=[]
String[] array sealed=false modifiers=[public abstract final]
double primitive sealed=false modifiers=[public abstract final]
List interface sealed=false modifiers=[public abstract interface]
How it works:
isAnnotation()must be checked beforeisInterface(), because every annotation type is also an interface.isSealed()(Java 17+) istrueonly forPayment.CardisfinalandUpiisnon-sealed;non-sealedis a compile-time keyword and has no modifier bit, so it does not appear.- Interfaces and annotations always report
abstract interface;Listalso showspublicbecause it is declared public, while these sample types are package-private. Top-level enums and records reportfinal. Arrays and primitives reportpublic abstract final, a JVM convention meaning they can neither be subclassed nor created with a constructor. Modifieralso has single checks such asModifier.isAbstract(mods),Modifier.isFinal(mods)andModifier.isPublic(mods).
| Method | true when the type is |
|---|---|
isInterface() | An interface or annotation type |
isAnnotation() | An annotation type |
isEnum() | An enum |
isRecord() | A record (Java 16+) |
isSealed() | A sealed class or interface (Java 17+) |
isArray() / isPrimitive() | An array type / int, double, void and the other primitives |
isMemberClass() / isLocalClass() / isAnonymousClass() | Nested in a class / declared in a method / unnamed |
isSynthetic() / isHidden() | Generated by the compiler / a hidden class such as a lambda's |
Superclass and Interfaces: Walking the Class Hierarchy
getSuperclass() returns the direct parent class, and getInterfaces() returns the interfaces a type lists directly in its implements (or, for an interface, extends) clause. isAssignableFrom and isInstance are the reflective versions of instanceof.
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
interface Payable { }
class Employee implements Serializable { }
class Manager extends Employee implements Payable, Comparable<Manager> {
public int compareTo(Manager other) {
return 0;
}
}
public class Hierarchy {
public static void main(String[] args) {
Class<?> type = Manager.class;
System.out.print("Superclass chain: ");
for (Class<?> current = type; current != null; current = current.getSuperclass()) {
System.out.print(current.getSimpleName() + (current.getSuperclass() != null ? " -> " : "\n"));
}
System.out.println("Direct interfaces: "
+ Arrays.stream(type.getInterfaces()).map(Class::getSimpleName).toList());
System.out.println("Interface superclass: " + Payable.class.getSuperclass());
System.out.println("Employee.isAssignableFrom(Manager): " + Employee.class.isAssignableFrom(Manager.class));
System.out.println("Manager.isAssignableFrom(Employee): " + Manager.class.isAssignableFrom(Employee.class));
System.out.println("Serializable.isInstance(new Manager()): " + Serializable.class.isInstance(new Manager()));
System.out.println("List.isAssignableFrom(ArrayList): " + List.class.isAssignableFrom(ArrayList.class));
}
}
Output:
Superclass chain: Manager -> Employee -> Object
Direct interfaces: [Payable, Comparable]
Interface superclass: null
Employee.isAssignableFrom(Manager): true
Manager.isAssignableFrom(Employee): false
Serializable.isInstance(new Manager()): true
List.isAssignableFrom(ArrayList): true
How it works:
- The loop follows
getSuperclass()until it returnsnull, which happens afterObject. Interfaces, primitives andObjectitself all returnnull. getInterfaces()lists onlyPayableandComparable.Serializableis not there, becauseManagerinherits it fromEmployeerather than declaring it.A.isAssignableFrom(B)asks "can aBbe stored in a variable of typeA?". It is the class-to-class form ofinstanceof, whileA.isInstance(object)works on an object.
Reading Generic Type Information
Because of type erasure, an ArrayList<String> object does not know it holds strings. But generic types written in declarations, such as extends ArrayList<String> or implements Function<String, Double>, are stored in the class file and can be read with the getGenericX methods.
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.function.Function;
class CourseList extends ArrayList<String> { }
class PriceParser implements Function<String, Double> {
public Double apply(String text) {
return Double.parseDouble(text);
}
}
public class GenericMetadata {
public static void main(String[] args) {
System.out.println("getSuperclass(): " + CourseList.class.getSuperclass());
Type generic = CourseList.class.getGenericSuperclass();
System.out.println("getGenericSuperclass(): " + generic);
ParameterizedType parameterized = (ParameterizedType) generic;
System.out.println("raw type: " + parameterized.getRawType().getTypeName()
+ ", type argument: " + parameterized.getActualTypeArguments()[0].getTypeName());
ParameterizedType function = (ParameterizedType) PriceParser.class.getGenericInterfaces()[0];
Type[] arguments = function.getActualTypeArguments();
System.out.println("Function input = " + arguments[0].getTypeName()
+ ", output = " + arguments[1].getTypeName());
ArrayList<Integer> plainList = new ArrayList<>();
System.out.println("Runtime list type parameter: " + plainList.getClass().getTypeParameters()[0]);
}
}
Output:
getSuperclass(): class java.util.ArrayList
getGenericSuperclass(): java.util.ArrayList<java.lang.String>
raw type: java.util.ArrayList, type argument: java.lang.String
Function input = java.lang.String, output = java.lang.Double
Runtime list type parameter: E
How it works:
getSuperclass()returns the erasedArrayList.getGenericSuperclass()returns aTypethat keeps<String>.- When the type is generic, that
Typeis aParameterizedType.getRawType()givesArrayListandgetActualTypeArguments()givesString. getGenericInterfaces()works the same way forimplementsclauses, revealingFunction<String, Double>.plainListwas created withnew ArrayList<>(), which is not a declaration of a subclass, so only the type variableEis available. TheIntegerexists only in the source code.
Note: This is why libraries such as Jackson and Gson ask you to write
new TypeReference<List<Course>>() { }. The{ }creates an anonymous subclass, and its generic superclass carriesList<Course>into the runtime.
Enum, Record, Sealed and Nested Type Metadata
Special kinds of types have their own metadata methods.
import java.lang.reflect.RecordComponent;
import java.util.Arrays;
public class MemberMetadata {
enum Status { DRAFT, PUBLISHED, ARCHIVED }
record Lesson(int number, String title, Status status) { }
sealed interface Result permits Result.Ok, Result.Failed {
record Ok(String value) implements Result { }
record Failed(String reason) implements Result { }
}
public static void main(String[] args) {
System.out.println("Enum constants: " + Arrays.toString(Status.class.getEnumConstants()));
for (RecordComponent component : Lesson.class.getRecordComponents()) {
System.out.println("Record component: " + component.getType().getSimpleName() + " "
+ component.getName() + " via " + component.getAccessor().getName() + "()");
}
System.out.println("Permitted: " + Arrays.stream(Result.class.getPermittedSubclasses())
.map(Class::getSimpleName).toList());
System.out.println("Lesson declared in: " + Lesson.class.getDeclaringClass().getSimpleName());
System.out.println("Nested types: " + Arrays.stream(MemberMetadata.class.getDeclaredClasses())
.map(Class::getSimpleName).sorted().toList());
System.out.println("String enum constants: " + String.class.getEnumConstants());
}
}
Output:
Enum constants: [DRAFT, PUBLISHED, ARCHIVED]
Record component: int number via number()
Record component: String title via title()
Record component: Status status via status()
Permitted: [Ok, Failed]
Lesson declared in: MemberMetadata
Nested types: [Lesson, Result, Status]
String enum constants: null
How it works:
getEnumConstants()returns the enum's values in declaration order, ornullfor a type that is not an enum.getRecordComponents()returns the components in declaration order. Each one knows its type, name and generated accessor method.getPermittedSubclasses()lists the classes allowed by asealed ... permitsclause. Pattern-matching libraries use it to check that every case is handled.getDeclaringClass()returns the class a member type is nested in, andgetDeclaredClasses()returns all member types of a class.
Package, Module and Class Loader Metadata
Every class belongs to a package, a module and a class loader. This metadata tells you where a class came from.
public class RuntimeMetadata {
public static void main(String[] args) {
Class<?>[] types = {RuntimeMetadata.class, String.class, java.sql.Connection.class};
for (Class<?> type : types) {
Module module = type.getModule();
ClassLoader loader = type.getClassLoader();
System.out.printf("%-16s package=%-11s module=%-10s loader=%s%n",
type.getSimpleName(),
"\"" + type.getPackageName() + "\"",
module.isNamed() ? module.getName() : "(unnamed)",
loader == null ? "bootstrap" : loader.getName());
}
}
}
Output:
RuntimeMetadata package="" module=(unnamed) loader=app
String package="java.lang" module=java.base loader=bootstrap
Connection package="java.sql" module=java.sql loader=platform
How it works:
- Your own class lives in the default package (
"") and the unnamed module, the module for everything on the classpath. Stringlives in the named modulejava.base. Its class loader is the bootstrap loader, which Java represents asnull.java.sql.Connectionis loaded by the platform loader in modulejava.sql, and your classes by the app loader. Modules are covered in Java Modules.
Real-World Example: A javap-Style Class Inspector
The JDK tool javap prints a summary of a compiled class. This example builds a small version with class metadata. It also shows a detail that surprises many developers: the compiler adds hidden bridge methods for generics, and tools must filter them out.
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.stream.Collectors;
interface Billable {
double total();
}
abstract class Product implements Comparable<Product> {
protected final String sku;
protected Product(String sku) {
this.sku = sku;
}
}
final class OnlineCourse extends Product implements Billable, Serializable {
public static final double GST_RATE = 0.18;
private final double basePrice;
private int enrolled;
public OnlineCourse(String sku, double basePrice) {
super(sku);
this.basePrice = basePrice;
}
OnlineCourse(String sku) {
this(sku, 999.0);
}
public double total() {
return basePrice * (1 + GST_RATE);
}
public void enroll(int seats) {
enrolled += seats;
}
public int compareTo(Product other) {
return sku.compareTo(other.sku);
}
private static String format(double amount) {
return String.format("%.2f", amount);
}
}
class ClassInspector {
static String simple(Type type) {
return type.getTypeName().replaceAll("\\b[a-z]\\w*\\.", ""); // drop package prefixes
}
static void collectInterfaces(Class<?> type, Set<String> found) {
for (Class<?> current = type; current != null; current = current.getSuperclass()) {
for (Class<?> anInterface : current.getInterfaces()) {
found.add(anInterface.getSimpleName());
collectInterfaces(anInterface, found);
}
}
}
static String params(Class<?>[] types) {
return Arrays.stream(types).map(Class::getSimpleName).collect(Collectors.joining(", "));
}
static void describe(Class<?> type) {
// 1. declaration line
String kind = type.isInterface() ? "interface" : type.isRecord() ? "record" : type.isEnum() ? "enum" : "class";
String modifiers = Modifier.toString(type.getModifiers() & ~Modifier.INTERFACE);
String implementsList = Arrays.stream(type.getGenericInterfaces())
.map(ClassInspector::simple).collect(Collectors.joining(", "));
System.out.println(modifiers + " " + kind + " " + type.getSimpleName()
+ " extends " + simple(type.getGenericSuperclass())
+ " implements " + implementsList + " {");
// 2. every interface, including inherited ones
Set<String> allInterfaces = new LinkedHashSet<>();
collectInterfaces(type, allInterfaces);
System.out.println(" // all interfaces: " + allInterfaces);
// 3. fields
Field[] fields = type.getDeclaredFields();
Arrays.sort(fields, Comparator.comparing(Field::getName));
for (Field field : fields) {
System.out.println(" " + Modifier.toString(field.getModifiers()) + " "
+ field.getType().getSimpleName() + " " + field.getName() + ";");
}
// 4. constructors
Constructor<?>[] constructors = type.getDeclaredConstructors();
Arrays.sort(constructors, Comparator.comparing(Constructor::getParameterCount));
for (Constructor<?> constructor : constructors) {
String access = Modifier.toString(constructor.getModifiers());
System.out.println(" " + (access.isEmpty() ? "" : access + " ") + type.getSimpleName()
+ "(" + params(constructor.getParameterTypes()) + ");");
}
// 5. methods, without compiler-generated bridges
Method[] methods = type.getDeclaredMethods();
Arrays.sort(methods, Comparator.comparing(Method::getName)
.thenComparing(method -> params(method.getParameterTypes())));
int bridges = 0;
for (Method method : methods) {
if (method.isBridge()) {
bridges++;
continue;
}
System.out.println(" " + Modifier.toString(method.getModifiers()) + " "
+ method.getReturnType().getSimpleName() + " " + method.getName()
+ "(" + params(method.getParameterTypes()) + ");");
}
System.out.println(" // skipped " + bridges + " bridge method(s)");
System.out.println("}");
}
}
public class Inspector {
public static void main(String[] args) {
ClassInspector.describe(OnlineCourse.class);
}
}
Output:
final class OnlineCourse extends Product implements Billable, Serializable {
// all interfaces: [Billable, Serializable, Comparable]
public static final double GST_RATE;
private final double basePrice;
private int enrolled;
OnlineCourse(String);
public OnlineCourse(String, double);
public int compareTo(Product);
public void enroll(int);
private static String format(double);
public double total();
// skipped 1 bridge method(s)
}
How it works:
- Declaration line.
getModifiers()givesfinal, the kind comes from theisX()checks, andgetGenericSuperclass()andgetGenericInterfaces()supply theextendsandimplementsparts. Thesimplehelper strips package prefixes such asjava.io.with a regular expression. - All interfaces.
getInterfaces()only returns direct interfaces, socollectInterfaceswalks up the superclass chain and into super-interfaces. That is how it findsComparable, whichOnlineCourseinherits fromProduct. - Fields and constructors.
getDeclaredFields()andgetDeclaredConstructors()return every access level. The package-private constructor has no modifier keyword at all. Both arrays are sorted because their order is not guaranteed. - Bridge methods.
ProductimplementsComparable<Product>, whose erased method iscompareTo(Object). To make that work, the compiler secretly adds acompareTo(Object)method toOnlineCoursethat callscompareTo(Product).getDeclaredMethods()returns it, andisBridge()lets the inspector skip it. - Private static helpers.
formatappears withprivate static, showing that reflection sees every declared member, not just the public API.
The next lesson, Java Dynamic Objects, uses this metadata to decide which class to instantiate and how, building objects from names read at runtime.