4

How to get the main class name in any point of my java execution. all that i wanted is i need to get the class name from where my execution has started. Example,

package mypackage;
class A
{
public static sayName()
{
 System.out.println("Here i have to print the class name B");
}
}


package test;
import mypackage.A;

class B
{
public static void main()
{
A.sayName();
}
}

Thanks in advance

Karthikeyan
  • 2,634
  • 5
  • 30
  • 51

3 Answers3

3

See if this works.

StackTraceElement[] stack = Thread.currentThread ().getStackTrace ();
StackTraceElement main = stack[stack.length - 1];
String mainClass = main.getClassName ();

But I am not sure if it will work if execution of this code has another thread of control other than main thread.

Vallabh Patade
  • 4,960
  • 6
  • 31
  • 40
0

Try this

public static String getMainClassName()
{
  for(final Map.Entry<String, String> entry : System.getenv().entrySet())
  {
    if(entry.getKey().startsWith("JAVA_MAIN_CLASS"))
      return entry.getValue();
  }
  throw new IllegalStateException("Cannot determine main class.")
}

This might work but it's not portable between JVMs.

harikrishnan.n0077
  • 1,927
  • 4
  • 21
  • 27
0

I'll create additional holder class which will hold main class name. Something like that:

public class MainClassHolder{
    private static String className = null;

    public static void setClassName(String name) {
         className = name;
    }
    public static String getClassName() {
         return className;
    }
} 

Then in main methot you'll set up className into holder

package mypackage;
class A
{
public static sayName()
{
 System.out.println(MainClassHolder.getClassName());
}
}


package test;
import mypackage.A;

class B
{
public static void main()
{
    MainClassHolder.setClassName(B.class.getName());
    A.sayName();
}
}
Timofei
  • 420
  • 1
  • 5
  • 14
  • Yeah., Nice idea. But when we are working in a project that more conscious about memory, this idea won't be a nice solution. Anyway, thanks for the effort.If i get any issue in getting stack trace., let me use this solution. Thanks for the effort. – Karthikeyan Dec 26 '12 at 05:46
  • @Karthikeyan,I'll not worry about memory. There is just one class with one static field. But if even this is critical for you - that's not very nice solution. – Timofei Dec 26 '12 at 05:55
  • You were right, i have got stuck with above solution when i ran the script via testing framework, In which, some class have been called before the main class, so stack[0] does not return my main class. you were awesome. Thanks for the solution. – Karthikeyan Mar 03 '13 at 10:05