Is there a way to check to see if the project that is currently running is a .jar or .war file? I am trying to get the class path but it of course is different based on whether it is a .war file or not.
String classPath = new File(Class.class.getProtectionDomain().getCodeSource().getLocation()
.toURI()).getPath();
Is there a way to determine if a project that is running is a
.waror a.jarfile?
I think that the answer is "no there isn't".
First ... what does it mean to "run a .war"?
Out of the box Java SE does not understand WAR files. java -cp my.war ... won't work. WAR files are a Java EE thing.
Likewise, an out of the box Java EE (or Jakarta EE) web container cannot run an ordinary JAR file with a public static void main(String[]) entry point.
In a typical Java EE container you don't directly "run" a WAR file. Instead you typically deploy it to the Java EE container (e.g. Tomcat, Websphere, etc). The container will then unpack the WAR into a directory and run the webapp from that directory, using a classloader that reads JAR files and .class files it finds within the directory.
(This is why the code in your question is unlikely to work. Resources on the webapp's classpath probably won't have war: URIs. They will have jar: or file: URIs ... referring to the unpacked WAR contents.)
But even if you call what (say) Tomcat does "running a WAR file" there is still an issue. With Tomcat can configure your IDE to populate the webapp directory directly, avoiding the need to create a WAR file at all. Or (shudder!) you can do your development in the Tomcat webapp dir directly.
As far as I am aware, a webapp cannot distinguish the two modes of deployment, and (therefore) cannot tell if it is running out of a JAR file or a WAR file.
On the other hand, a Java application (or library) can probably figure out if it is running in a Java EE (or Jakarta EE) container. If it is, it will be able to (for example) load Servlet classes using reflection.
If we are talking about a specific framework (such as Spring Boot) that supports both running JAR and WAR-based applications, then the app may be able to use that framework's capabilities to distinguish the two cases. (But it is probably not a useful distinction to make ...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With