Skip to content

Instantly share code, notes, and snippets.

@audinue
Created May 18, 2023 10:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save audinue/d4a1f2275b5a470cb490f19c94876f17 to your computer and use it in GitHub Desktop.
Save audinue/d4a1f2275b5a470cb490f19c94876f17 to your computer and use it in GitHub Desktop.
Desktop Java base class.
package com.example;
import java.io.InputStream;
import java.net.URLClassLoader;
import java.util.jar.Manifest;
public class Foo {
public void bar() {
}
public static void main(String[] args) throws Exception {
URLClassLoader loader = (URLClassLoader) Foo.class.getClassLoader();
String command = System.getProperty("sun.java.command");
int index = command.indexOf(" ");
if (index > -1) {
command = command.substring(0, index);
}
if (command.toLowerCase().endsWith(".jar")) {
try (InputStream in = loader
.findResource("META-INF/MANIFEST.MF")
.openStream()) {
command = new Manifest(in)
.getMainAttributes()
.getValue("Main-Class");
}
}
Foo foo = (Foo) loader.loadClass(command).newInstance();
foo.bar();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment