Java Reflection: The Class Class, Exceptions Primer and Loading Resources
Start with Java reflection: what it is for, getting Class objects with getClass, Class.forName and .class literals, odd array type names, comparing Class objects, creating instances by name, a primer on checked exceptions, and loading resources with getResource and getResourceAsStream.
kvi5hnuCode Sprout team member12 min readOn this page
Reflection is the ability of a running program to look at its own types: which classes exist, what fields and methods they declare, and to use them without knowing them at compile time. With the reflection API you can:
- analyze the capabilities of classes at runtime (fields, methods, constructors),
- inspect objects at runtime, for example to write one
toStringmethod that works for all classes, - implement generic array manipulation code,
- invoke methods through
Methodobjects, much like function pointers in C++.
Application code rarely needs reflection directly; its main users are frameworks and tools. Frameworks such as Spring, Hibernate/JPA, Jackson, JUnit and IDEs all use it heavily: they discover your classes, read annotations, create objects and call methods they never knew about at compile time. If you write applications rather than frameworks, a quick read of the later reflection articles is enough for now. This first article covers the basics that every Java programmer meets: the Class class and loading resources.
The Class Class
Every object knows its class at run time; that's how the JVM picks the right method during dynamic binding. Java exposes this knowledge as objects of type java.lang.Class (yes, a class named Class). Any object hands you its Class object through getClass():
Employee e = . . .;
Class<? extends Employee> cl = e.getClass();
A Class object is a description of one type: its name, its superclass, its fields, methods and constructors. The simplest query is getName():
System.out.println(e.getClass().getName() + " " + e.getName());
// Manager Omar Haddad (if e is a manager)
// Employee Omar Haddad (if e is an ordinary employee)
For a class inside a package, getName() returns the fully qualified name:
var queue = new ArrayDeque<String>();
Class<?> cl = queue.getClass();
String name = cl.getName(); // "java.util.ArrayDeque"
getSimpleName() gives ArrayDeque and getPackageName() gives java.util.
Three ways to obtain a Class object
![Three ways to get a Class object: obj.getClass(), Class.forName with a name, and the .class literal all return the same single Class object; int.class is named int, void.class void, Double[].class [Ljava.lang.Double; and int[].class [I](https://code-sprout-content.laxmi.solutions/asset/2026/11/durwcean7eam42zg.png)
-
From an object:
obj.getClass()returns the class of the object's runtime type. -
From a name: the static method
Class.forNamereturns theClassobject for a fully qualified class name:javaString className = "java.util.ArrayDeque"; Class\<?> cl = Class.forName(className);That's how plugins and configuration-driven code work: the class name arrives as text at run time. If no class or interface of that name can be found,
forNamethrowsClassNotFoundException, a checked exception. See the exceptions primer below for how to deal with it. -
From a type known at compile time: if
Tis any Java type (orvoid), thenT.classis the matching class object:javaClass\<?> cl1 = ArrayDeque.class; // with import java.util.ArrayDeque Class\<?> cl2 = int.class; Class\<?> cl3 = Double[].class;
Strictly speaking, a Class object describes a type, and not every type is a class: int.class exists and is a Class object, although int is a primitive.
Strange names for array types
For array types, getName returns the JVM's internal spelling, which looks odd at first:
| Expression | getName() | getSimpleName() |
|---|---|---|
Double[].class | [Ljava.lang.Double; | Double[] |
int[].class | [I | int[] |
String[][].class | [[Ljava.lang.String; | String[][] |
int.class | int | int |
The [ means "array of", L…; wraps a class name, and single letters encode primitive types (I int, J long, D double, Z boolean, B byte, C char, S short, F float). This is the JVM's internal descriptor format, and you'll see it in stack traces and in the default toString of arrays ([I@1b6d3586). For readable names use getSimpleName() or getTypeName() (java.lang.Double[]).
Comparing Class objects
Within one class loader, each type has exactly one Class object, so comparing with == is correct:
if (e.getClass() == Employee.class) . . .
It is true only for objects whose class is exactly Employee; a Manager fails it. e instanceof Employee, in contrast, accepts subclasses. This is exactly the distinction behind the getClass versus instanceof choice in writing equals.
Creating an object from a Class object
A Class object can also create instances. Ask it for a Constructor and call newInstance:
var className = "java.util.ArrayDeque"; // any class with a public no-arg constructor
Class<?> cl = Class.forName(className);
Object obj = cl.getConstructor().newInstance();
Without a matching public no-argument constructor, getConstructor() throws NoSuchMethodException. You'll see how to invoke other constructors in the next article.
A Primer on Declaring Exceptions
Exceptions get a full treatment in the exceptions part, but reflection methods throw them all the time, so here's what you need now.
A method that hits a problem it can't handle throws an exception. Some caller further up may catch it and recover; if nobody does, the program stops and prints the exception and a stack trace, as you have seen with NullPointerException and ArrayIndexOutOfBoundsException.
There are two kinds of exceptions:
- Unchecked exceptions (subclasses of
RuntimeException, such asNullPointerException). The compiler doesn't check whether you provide a handler. You should spend your effort avoiding these mistakes rather than handling them. - Checked exceptions (such as
ClassNotFoundExceptionorIOException). The compiler checks that you are aware of them and have prepared for the consequences.
The simplest strategy for a checked exception is to declare that your method may throw it, with a throws clause. Any method that calls Class.forName must declare ClassNotFoundException, or handle it:
public static void doSomethingWithClass(String name)
throws ReflectiveOperationException {
Class<?> cl = Class.forName(name); // might throw an exception
// do something with cl
}
If this method is called and the class doesn't exist, the method is terminated and the exception passes to the caller. If main declares it too and nobody catches it, the program terminates with a stack trace, much like an unchecked exception.
ReflectiveOperationException is the common superclass of ClassNotFoundException, NoSuchMethodException, NoSuchFieldException, IllegalAccessException, InstantiationException and InvocationTargetException. Declaring it covers every checked exception that reflection code typically throws.
To handle the exception instead, use try/catch:
try {
Class<?> cl = Class.forName(name);
. . .
} catch (ClassNotFoundException ex) {
System.out.println("No such class: " + ex.getMessage());
}
Everything So Far in One Program
import java.util.Scanner;
public class Solution {
public static void main(String[] args) throws ReflectiveOperationException {
Employee e = new Manager("Omar Haddad");
System.out.println(e.getClass().getName() + " " + e.getName());
var in = new Scanner("");
Class<?> cl = in.getClass();
System.out.println(cl.getName() + " / " + cl.getSimpleName() + " / " + cl.getPackageName());
Class<?> byName = Class.forName("java.util.Scanner");
System.out.println(byName == cl); // one Class object per type
Class<?> cl1 = Scanner.class;
Class<?> cl2 = int.class;
Class<?> cl3 = Double[].class;
System.out.println(cl1.getName() + " " + cl2.getName() + " " + cl3.getName() + " " + int[].class.getName());
System.out.println(Double[].class.getSimpleName() + " " + void.class + " " + int.class.isPrimitive());
System.out.println((e.getClass() == Employee.class) + " " + (e instanceof Employee));
System.out.println(e.getClass().getSuperclass().getName());
System.out.println((Roast.LIGHT.getClass() == Roast.class) + " " + (Roast.FRENCH.getClass() == Roast.class)
+ " " + (Roast.FRENCH.getDeclaringClass() == Roast.class));
// construct an object from a class name
Object list = Class.forName("java.util.ArrayList").getConstructor().newInstance();
System.out.println(list.getClass().getName() + " " + list);
try {
Class.forName("com.example.DoesNotExist");
} catch (ClassNotFoundException ex) {
System.out.println("ClassNotFoundException: " + ex.getMessage());
}
// resources
System.out.println(String.class.getResource("String.class"));
System.out.println(Solution.class.getResourceAsStream("missing.txt"));
}
}
class Employee {
private final String name;
Employee(String name) { this.name = name; }
String getName() { return name; }
}
class Manager extends Employee {
Manager(String name) { super(name); }
}
enum Roast {
LIGHT, MEDIUM, DARK,
FRENCH {
@Override public String toString() { return "French roast"; }
}
}
Manager Omar Haddad
java.util.Scanner / Scanner / java.util
true
java.util.Scanner int [Ljava.lang.Double; [I
Double[] void true
false true
Employee
true false true
java.util.ArrayList []
ClassNotFoundException: com.example.DoesNotExist
jrt:/java.base/java/lang/String.class
null
The last two lines preview the next section: String.class itself is a resource inside the JDK's runtime image (the jrt: file system), and a resource that doesn't exist yields null.
Loading Resources
Classes often have associated data files, such as:
- image and sound files,
- text files with messages, templates or help pages,
- configuration files (
.properties, JSON, SQL scripts).
In Java, such an associated file is called a resource. For example, a start-up banner might show text from welcome.txt. The file shouldn't live in some arbitrary directory that may or may not exist on the user's machine. It belongs with the class files, typically packaged in the same JAR. The Class class provides a service for locating resources:
- Get the
Classobject of the class that has the resource, for exampleBannerApp.class. - If you need the location of the resource as a URL, call
getResource(name). - Otherwise, call
getResourceAsStream(name)to get anInputStreamfor reading the data.
The point is that the class loader remembers how to locate the class, so it can search for the associated resource in the same location. Whether the class came from a directory, a JAR file or the JDK's runtime image, the same code works.
Class<?> cl = BannerApp.class;
URL welcomeUrl = cl.getResource("welcome.txt");
System.out.println(welcomeUrl); // jar:file:...!/com/example/resources/welcome.txt
InputStream stream = cl.getResourceAsStream("welcome.txt");
var welcome = new String(stream.readAllBytes(), StandardCharsets.UTF_8);
If the resource isn't found, both methods return null. They don't throw exceptions or I/O errors, so check for null (or wrap with Objects.requireNonNull(stream, "welcome.txt missing") to fail with a clear message).
Relative and absolute resource names

- A name without a leading slash is relative to the package of the class: in
com.example.resources.BannerApp,"welcome.txt"meanscom/example/resources/welcome.txt, and"data/motd.txt"meanscom/example/resources/data/motd.txt. - A name with a leading
/is absolute:"/config/app.properties"is located from the root of the class path, in the same way that a class fileconfig/...would be found. - Resource names always use
/as the separator, on every operating system.
Here is a complete example. The resources sit next to the class in the source tree, the build copies them into the output directory (Maven and Gradle do this automatically for src/main/resources), and everything ends up in a JAR:
package com.example.resources;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class BannerApp {
public static void main(String[] args) throws IOException {
Class<?> cl = BannerApp.class;
URL welcomeUrl = cl.getResource("welcome.txt"); // same directory as the class
System.out.println("found at: " + welcomeUrl.getProtocol());
try (InputStream stream = cl.getResourceAsStream("welcome.txt")) {
System.out.print(new String(stream.readAllBytes(), StandardCharsets.UTF_8));
}
try (InputStream stream = cl.getResourceAsStream("data/motd.txt")) { // relative path
System.out.print(new String(stream.readAllBytes(), StandardCharsets.UTF_8));
}
try (InputStream stream = cl.getResourceAsStream("/config/app.properties")) { // absolute path
System.out.print(new String(stream.readAllBytes(), StandardCharsets.UTF_8));
}
}
}
$ javac -d classes src/com/example/resources/BannerApp.java
$ cp -r <resource files> classes/...
$ jar cvfe BannerApp.jar com.example.resources.BannerApp -C classes .
$ cd somewhere/else && java -jar BannerApp.jar
found at: jar
Welcome, crew member
Maintenance window: Sunday 02:00
greeting=hello
The program works from any working directory, because it never uses a file system path. The URL protocol is jar when the resource is inside a JAR, and file when it is in a plain directory. (The try (...) syntax closes the stream automatically; it's called try-with-resources and is covered in the exceptions part.)
Common questions
Should I use getClass() or .class?
Use .class when you know the type at compile time (String.class). It's checked by the compiler and never fails. Use getClass() when you need the runtime type of an object, which may be a subclass of its declared type.
Why does Class.forName initialise the class?
The one-argument Class.forName(name) loads and initialises the class, running its static initialisers. That is how old JDBC drivers registered themselves. To load a class without initialising it, use Class.forName(name, false, loader).
Why does getResourceAsStream return null in my IDE but work in the JAR (or the other way round)?
Usually the resource is in the wrong folder. It must be on the class path: put it in src/main/resources with Maven/Gradle, or let your IDE copy it into the output folder. Then check whether the name is relative to the class's package or absolute (leading /). ClassLoader.getResource names never start with /.
Can I read a resource as a Path or File?
Only if it happens to be in a plain directory. Inside a JAR, a resource isn't a file. Always read resources as streams (getResourceAsStream) or URLs. If an API really needs a file, copy the stream to a temporary file first.
Is reflection allowed in GraalVM native images? Only for classes and members registered in advance, through configuration files or framework metadata. Native images are compiled ahead of time and leave out code that isn't reachable. That's one reason modern frameworks reduce reflection or generate code at build time.
Summary
- Reflection lets a program analyze and manipulate classes at runtime. It's mainly for tool and framework builders.
- Every type has a unique
Classobject. Get it withobj.getClass(),Class.forName("pkg.Name")orT.class(also for primitives, arrays andvoid). getNamereturns names likejava.util.ArrayDeque, and descriptor names for arrays ([I,[Ljava.lang.Double;).getSimpleNameis readable.- Compare
Classobjects with==.e.getClass() == Employee.classis false for subclasses, unlikeinstanceof. cl.getConstructor().newInstance()creates an object.Class.newInstanceis deprecated.- Checked exceptions such as
ClassNotFoundExceptionmust be declared withthrows(or caught).ReflectiveOperationExceptioncovers the reflection family. getResourceandgetResourceAsStreamlocate data files next to a class, in a directory or JAR. Relative names are package-relative, a leading/means class path root, and missing resources returnnull.
Practice Questions
Employee e = new Manager(...). What do e.getClass() == Employee.class and e instanceof Employee return?
false and true. getClass() returns the exact runtime class Manager, while instanceof accepts subclasses.
What does String[][].class.getName() return, and how do you get a readable name?
[[Ljava.lang.String;. Use getSimpleName() (String[][]) or getTypeName() (java.lang.String[][]).
Why must a method calling Class.forName either catch or declare an exception, but a method that may divide by zero doesn't?
ClassNotFoundException is a checked exception, so the compiler insists you handle or declare it. ArithmeticException is unchecked (a RuntimeException), which you should prevent rather than declare.
Write code that creates an object from a class name read at runtime and prints its class, using the non-deprecated API.
static Object create(String name) throws ReflectiveOperationException {
Object obj = Class.forName(name).getConstructor().newInstance();
System.out.println(obj.getClass().getName());
return obj;
}
BannerApp is in package com.acme.app. Which file does getResourceAsStream("img/logo.png") open, and which does getResourceAsStream("/img/logo.png") open?
The first opens com/acme/app/img/logo.png (relative to the package). The second opens img/logo.png at the root of the class path.
Why load data with getResourceAsStream instead of new FileInputStream("welcome.txt")?
A file path depends on the current working directory and the user's machine, and it fails once the application is packaged in a JAR. Resources are found by the class loader wherever the class itself came from.
Previous: Java Pattern Matching: switch Patterns, Record Patterns and Guards
Next: Java Reflection: Analyzing Classes and Inspecting Objects at Runtime
Related reading
- Throwing Exceptions and Creating Custom Exception Classes in Java
- Java Reflection: Analyzing Classes and Inspecting Objects at Runtime
- Java Generics Inheritance Rules and Wildcards: extends, super and ?
- Java Generics: Generic Classes and Generic Methods
- Java Logging Handlers, Filters and Formatters: Configuring java.util.logging

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.