eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

1. Overview

JAR files are Java archives. We may include various JAR files as libraries when we build Java applications.

In this tutorial, we’ll explore how to find the JAR file and its full path from a given class.

2. Introduction to the Problem

Let’s say we have a Class object at runtime. Our goal is to find out which JAR file the class belongs to.

An example may help us understand the problem quickly. Let’s say we have the class instance of Guava‘s Ascii class. We want to create a method to find out the full path of the JAR file that holds the Ascii class.

We’ll mainly address two different methods to get the JAR file’s full path. Further, we’ll discuss their pros and cons.

For simplicity, we’ll verify the result by unit test assertions.

Next, let’s see them in action.

3. Using the getProtectionDomain() Method

Java’s class object provides the getProtectionDomain() method to obtain the ProtectionDomain object. Then, we can get the CodeSource through the ProtectionDomain object. The CodeSource instance will be the JAR file we’re looking for. Further, CodeSource.getLocation() method gives us the URL object of the JAR file. Finally, we can use the Paths class to get the full path of the JAR file.

3.1. Implementing the byGetProtectionDomain() Method

If we wrap all steps that we’ve mentioned above in a method, a couple of lines will do the job:

public class JarFilePathResolver {
    String byGetProtectionDomain(Class clazz) throws URISyntaxException {
        URL url = clazz.getProtectionDomain().getCodeSource().getLocation();
        return Paths.get(url.toURI()).toString();
    }
}

Next, let’s take the Guava Ascii class as an example to test if our method works as expected:

String jarPath = jarFilePathResolver.byGetProtectionDomain(Ascii.class);
assertThat(jarPath).endsWith(".jar").contains("guava");
assertThat(new File(jarPath)).exists();

As we can see, we’ve verified the returned jarPath through two assertions:

  • first, the path should point to the Guava JAR file
  • if jarPath is a valid full path, we can create a File object from jarPath, and the file should exist

If we run the test, it passes. So the byGetProtectionDomain() method works as expected.

3.2. Some Limitations of the getProtectionDomain() Method

As the code above shows, our byGetProtectionDomain() method is pretty compact and straightforward. However, if we read the JavaDoc of the getProtectionDomain() method, it says the getProtectionDomain() method may throw SecurityException.

We’ve written a unit test, and the test passes. This is because we’re testing the method in our local development environment. In our example, the Guava JAR is located in our local Maven repository. Therefore, no SecurityException was raised.

However, some platforms, for instance, Java/OpenWebStart and some application servers, may prohibit getting the ProtectionDomain object by calling the getProtectionDomain() method. Therefore, if we deploy our application to those platforms, our method will fail and throw SecurityException.

Next, let’s see another approach to get the JAR file’s full path.

4. Using the getResource() Method

We know that we call the Class.getResource() method to get the URL object of the resource of the class. So let’s start with this method to resolve the full path of the corresponding JAR file finally.

4.1. Implementing the byGetResource() Method

Let’s first have a look at the implementation and then understand how it works:

String byGetResource(Class clazz) {
    URL classResource = clazz.getResource(clazz.getSimpleName() + ".class");
    if (classResource == null) {
        throw new RuntimeException("class resource is null");
    }
    String url = classResource.toString();
    if (url.startsWith("jar:file:")) {
        // extract 'file:......jarName.jar' part from the url string
        String path = url.replaceAll("^jar:(file:.*[.]jar)!/.*", "$1");
        try {
            return Paths.get(new URL(path).toURI()).toString();
        } catch (Exception e) {
            throw new RuntimeException("Invalid Jar File URL String");
        }
    }
    throw new RuntimeException("Invalid Jar File URL String");
}

Compared to the byGetProtectionDomain approach, the method above looks complex. But in fact, it’s pretty easy to understand as well.

Next, let’s walk through the method quickly and understand how it works. For simplicity, we throw RuntimeException for various exception cases.

4.2. Understanding How It Works

First, we call the Class.getResource(className) method to get the URL of the given class.

If the class is from a JAR file on the local filesystem, the URL string should be in this format:

jar:file:/FULL/PATH/TO/jarName.jar!/PACKAGE/HIERARCHY/TO/CLASS/className.class

For example, here’s the URL string of Guava’s Ascii class on a Linux system:

jar:file:/home/kent/.m2/repository/com/google/guava/guava/31.0.1-jre/guava-31.0.1-jre.jar!/com/google/common/base/Ascii.class

As we can see, the full path of the JAR file lies in the middle of the URL string.

As the file URL format on different operating systems may differ, we’ll extract the “file:…..jar” part, convert it back to a URL object, and use the Paths class to get the path as a String.

We build a regex and use String‘s replaceAll() method to extract the part we need: String path = url.replaceAll(“^jar:(file:.*[.]jar)!/.*”, “$1”);

Next, similar to the byGetProtectionDomain() approach, we get the final result using the Paths class.

Now, let’s create a test to verify if our method works with Guava’s Ascii class:

String jarPath = jarFilePathResolver.byGetResource(Ascii.class);
assertThat(jarPath).endsWith(".jar").contains("guava");
assertThat(new File(jarPath)).exists();

The test will pass if we give it a run.

5. Combining the Two Methods

So far, we’ve seen two approaches to solve the problem. The byGetProtectionDomain approach is straightforward and reliable, but may fail on some platforms due to security limitations.

On the other hand, the byGetResource method doesn’t have security issues. However, we need to do more manual manipulations, such as handling different exception cases and extracting the URL string of the JAR file using regex.

5.1. Implementing the getJarFilePath() Method

We can combine the two methods. First, let’s try to resolve the JAR file’s path with byGetProtectionDomain(). If it fails, we call the byGetResource() method as a fallback:

String getJarFilePath(Class clazz) {
    try {
        return byGetProtectionDomain(clazz);
    } catch (Exception e) {
        // cannot get jar file path using byGetProtectionDomain
        // Exception handling omitted
    }
    return byGetResource(clazz);
}

5.2. Testing the getJarFilePath() Method

To simulate byGetProtectionDomain() throwing SecurityException in our local development environment, let’s add Mockito dependency and partially mock the JarFilePathResolver using the @Spy annotation:

@ExtendWith(MockitoExtension.class)
class JarFilePathResolverUnitTest {
    @Spy
    JarFilePathResolver jarFilePathResolver;
    ...
}

Next, let’s first test the scenario that the getProtectionDomain() method doesn’t throw a SecurityException:

String jarPath = jarFilePathResolver.getJarFilePath(Ascii.class);
assertThat(jarPath).endsWith(".jar").contains("guava");
assertThat(new File(jarPath)).exists();
verify(jarFilePathResolver, times(1)).byGetProtectionDomain(Ascii.class);
verify(jarFilePathResolver, never()).byGetResource(Ascii.class);

As the code above shows, apart from testing whether the path is valid, we also verify that if we can get the JAR file’s path by the byGetProtectionDomain() method, the byGetResource() method should never be called.

Of course, if byGetProtectionDomain() throws SecurityException, the two methods will be called once:

when(jarFilePathResolver.byGetProtectionDomain(Ascii.class)).thenThrow(new SecurityException("not allowed"));
String jarPath = jarFilePathResolver.getJarFilePath(Ascii.class);
assertThat(jarPath).endsWith(".jar").contains("guava");
assertThat(new File(jarPath)).exists();
verify(jarFilePathResolver, times(1)).byGetProtectionDomain(Ascii.class);
verify(jarFilePathResolver, times(1)).byGetResource(Ascii.class);

If we execute the tests, both tests pass.

6. Conclusion

In this article, we’ve learned how to get a JAR file’s full path from a given class.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)