Click to See Complete Forum and Search --> : java


jon787
03-02-2003, 12:56 AM
From within a java program how do I obtain the name of the class the JVM is started with?

stoe
03-02-2003, 01:42 AM
public class Test
{
public static void main(String[] args)
{
TestB.aMethod();
}
}

class TestB
{
public static void aMethod()
{
TestC.aMethod();
}
}

class TestC
{
public static void aMethod()
{
Exception e = new Exception();
StackTraceElement[] stktr = e.getStackTrace();

try
{
Class mainClass = Class.forName(stktr[stktr.length-1].getClassName());
System.out.println(mainClass.getName());
}
catch(Exception e2) {}
}
}

perhaps there is a cleaner way to get the information you need, but i do not know of such a way.

jon787
03-02-2003, 02:35 AM
Thanks for the idea, but it didn't work out the way I need it too.

Here is some code

public class Foo {
public static void main(String args[]) {
...do something...
}
...do something....
}

class Bar extends Foo {
....do something....
}


So if the JVM is started:
java Foo
An instance of Foo is created and run
if it is started:
java Bar
An instance of Bar is created and run.

I don't want to have to override the main() method each time I extend the class.

Chipmunk
03-03-2003, 11:17 AM
Maybe you could have a class Snafu and then pass a parameter to it on startup, either Foo or Bar. The Snafu main method would be able to parse the arguements passed to it and then take appropriate action depending on the value of the parameter.

Just a suggestion.:)

jon787
03-04-2003, 02:58 AM
I've worked the original response into a kludge that works. It just doesn't work from any event driven part of the program (Listeners and such) so there is some kludging involved.

According to the people on the Java Developer Forums the information is NOT available in any other way.