Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4321980
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 21, 20262026-05-21T08:48:55+00:00 2026-05-21T08:48:55+00:00

When a subclass inherits main() from a superclass, is it possible to determine the

  • 0

When a subclass inherits main() from a superclass, is it possible to determine the actual class invoked on the command-line? For example, consider the following two classes, in which main is implemented by A and inherited by B:

public class A {

    public static void main(String[] args) throws Exception {
        // Replace with <some magic here> to determine the class 
        //    invoked on the command-line
        final Class<? extends A> c = A.class;
        System.out.println("Invoked class: " + c.getName());

        final A instance = c.newInstance();
        // Do something with instance here...
    }
}

public class B extends A {
}

We can invoke B successfully (i.e., B does ‘inherit’ main – at least in whatever sense static methods can be inherited), but I have not found a method to determine the actual class invoked by the user:

$ java -cp . A
Invoked class: A

$ java -cp . B
Invoked class: A

The closest I’ve come is to require that the subclass implement main() and call a helper method in the superclass, which then reads the thread stack to determine the calling class:

public class AByStack {

    public static void run(String[] args) throws Exception {
        // Read the thread stack to find the calling class
        final Class<? extends AByStack> c = (Class<? extends AByStack>)
            Class.forName(Thread.currentThread().getStackTrace()[2].getClassName());
        System.out.println("Invoked class: " + c.getName());

        final AByStack instance = c.newInstance();
        // Do something with instance here...
    }

    public static void main(String[] args) throws Exception {
        run(args);
    }
}

public class BByStack extends AByStack {

    public static void main(String[] args) throws Exception {
        // Call the master 'run' method
        run(args);
    }
}

This method works:

$ java -cp . AByStack
Invoked class: AByStack

$ java -cp . BByStack
Invoked class: BByStack

But I’d really like to eliminate the requirement that subclasses implement main() (yes, call me picky…). I don’t mind if it requires some ugly code, since it will be implemented once and buried in the base class, and I’m mostly interested in Sun/Oracle VMs, so I’d be willing to consider using a private sun.misc class or something similar.

But I do want to avoid platform-dependencies. For example, on Linux, we can look at /proc/self/cmdline, but that’s of course not portable to Windows (I’m not sure about Mac OS – I don’t have my Mac with me at the moment to test this trick). And I think JNI and JVMTI are out for the same reason. I might be wrong about JVMTI, but it looks to me like it would require a C wrapper. If not, perhaps we could use that interface somehow.

This question was asked years ago at http://www.coderanch.com/t/375326/java/java/Getting-command-line-class. The best answer there required a static initializer block in each subclass – a different, but similar requirement on the subclass author to the main calling run() solution I demonstrated. But I haven’t seen more recent discussions; I’m hopeful that current VMs might allow access to information that wasn’t available at the time of that discussion.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-21T08:48:56+00:00Added an answer on May 21, 2026 at 8:48 am

    Since I’ve wasted considerably more time investigating than the problem warranted, I’ll post my conclusions here.

    First, to try to reiterate the rationale for the question:

    I have abstracted argument-handling, I/O, and other shared tasks into an abstract superclass, which I expect others to extend. After performing argument parsing and shared setup, a static method in the superclass instantiates an instance of the subclass and calls its run() method.

    Authors of subclasses are encouraged to implement public static void main(String[]) and call the superclass’s primary entry point. But, unlike the requirement that all subclasses implement run(), we cannot enforce that requirement statically at compile time (since Java has no concept of an abstract static method).

    So I’m trying to implement a main(String[]) method in the superclass which can determine the name of the subclass which was requested on the command-line and instantiate the appropriate class.

    I’ve found two methods, both specific to the Sun / Oracle JVM.

    The first uses internal sun.jvmstat classes:

    import java.lang.management.ManagementFactory;
    import sun.jvmstat.monitor.MonitoredVmUtil;
    import sun.jvmstat.monitor.VmIdentifier;
    import sun.jvmstat.perfdata.monitor.protocol.local.LocalMonitoredVm;
    
    ...
    
    public static String jvmstatMainClass() {
        // Determine the VMID (on most platforms, this will be the PID)
        final String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
    
        // Connect to the virtual machine by VMID
        final VmIdentifier vmId = new VmIdentifier(pid);
        final LocalMonitoredVm lmVm = new LocalMonitoredVm(vmId, 1000);
    
        // Find the requested main-class
        String mainClass = MonitoredVmUtil.mainClass(lmVm, true);
    
        // And detach from the VM
        lmVm.detach();
    
        return mainClass;
    }
    

    The second uses Sun’s jps utility:

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    
    ...
    
    public static String jpsMainClass() {
        // Determine the VMID (on most platforms, this will be the PID)
        final String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
    
        // Execute the 'jps' utility
        final Process jps = Runtime.getRuntime().exec(new String[] { "jps", "-l" });
        final BufferedReader br = new BufferedReader(new InputStreamReader(jps.getInputStream()));
    
        // Parse the output of jps to find the current VM by PID
        for (String line = br.readLine(); line != null; line = br.readLine()) {
            final String[] split = line.split(" ");
            if (pid.equals(split[0])) {
                    return split[1];
                }
            }
        }
        return null;
    }
    

    Hopefully my wasted time will prove helpful to someone else.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Is it possible to have an entity class which inherits from another (abstract) entity
i'm trying to create a new class that inherits from an abstract superclass (contains
Isn't that subclass inherits everything from superclass true? But subclass could not access its
Is it possible to subclass and inherit from javascript Arrays? I'd like to have
If I derive my class from QObject (or a subclass), the Qt documentation says
I have a class that inherits from UIView, and this class has some controls
Using JavaScript how do I create a subclass that inherits values from the parent
Suppose a class Y publicly inherits a class X . Is it possible for
I have a subclassed UITableView, 'subclassChild' which inherits from another subclass 'subclassParent'. 'subclassParent' then
When a class extends another, it inherits all methods and variables of the superclass.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.