Answer the question
In order to leave comments, you need to log in
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) {
//...
}
}
public class Send extends Robot {
//... нет своего метода main
}
public class Recv extends Robot {
//... нет своего метода main
}
java -cp . Send
java -cp . Recv
Answer the question
In order to leave comments, you need to log in
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();
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;
}
}
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 questionAsk a Question
731 491 924 answers to any question