P
P
pqgg7nwkd42016-06-16 21:27:14
Java
pqgg7nwkd4, 2016-06-16 21:27:14

How to know which class is running from java command line?

Good afternoon.
There is a class:

public abstract class Robot {
  public static int main(String[] args) {
    //...
  }
}

And his two heirs:
public class Send extends Robot {
//... нет своего метода main
}

public class Recv extends Robot {
//... нет своего метода main
}

We launch:
java -cp . Send
java -cp . Recv

This starts Robot.main();
Question: How can I find out in Robot.main() which class I launched: Send or Recv?
Thank you.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Kosarev, 2016-06-17
@pqgg7nwkd4

Static methods are not inherited, so you can't get it through reflection.
Two options that came to my mind:
In the Recv and Send classes, describe your main methods that simply call Robot.main, then in Robot.main you can get information about the called class from the stack trace:

StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
stackTrace[stackTrace.length - 1].getClassName();

The second option is to look at the sun.java.command system variable, which points to the class that was launched.
The question is only in the practical application of this.

V
Vitaly Vitrenko, 2016-06-16
@Vestail

There is no way to achieve this through reflection. Can you do something like this

public abstract class Robot {
  protected static Class loaded;
  
  public static int main(String[] args) {
     System.out.println(loaded);
  }
}

public class Send extends Robot {
  static {
    loaded = loaded == null ? Send.class : loaded; 	
  }
}

D
Denis Zagaevsky, 2016-06-17
@zagayevskiy

Make it human.
The first is to get away from static as quickly as possible. You make the robot protected final void run(String[] arts){...here is the code from main...}
Secondly, you make the main method for each of the heirs - very simple. Inside it is one line - for example, new Send().run();
Now in run you can determine who you are by getClass.
But! It's pretty bad - when the ancestor knows about the descendants. You need to figure out how to leave everything in common in Robot, and take out all the differences in its descendants using polymorphism.
Inheriting static classes (having only static methods) is a little more than completely pointless.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question