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.
Presumably you want this so that some tool can be called with different names, but behave largely the same depending on the name it was invoked with? Or some similar magic?
In which case, you could simply have an actual main() method in all the sub-classes and delegate to a method which also takes the name of the invoked class:
public class Super {
protected void doMain(String invokee, String... args) {
System.out.println("I was invoked as: " + invokee);
}
}
public class ToolA {
public static void main(String... args) {
new Super().doMain("ToolA", args); // or ToolA.class.getName() to be refactor-proof
}
}
I think I would simply modify the signature of the run() method, and rather than using the call stack, implement main() in each subclass as:
public class BByStack extends AByStack {
public static void main(String[] args) throws Exception {
// Call the master 'run' method
run(BByStack.class, args);
}
}
If all you are doing is instantiating using the default constructor, I would even just pass in
new BByStack()
I don't know of any way to do what you're asking; the method is static, so you can't get a handle to this.getClass() or the like; if the method is not defined on the subclass, you also can't get that information from the stack.
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.
Related
I have the following code:
public class Application extends ApplicationManager{
public static void main(String[] args) {
ProcessUtility.enableProcessUtility();
new Application().start();
}
}
and the class ApplicationManager code:
public class ApplicationManager {
public ApplicationManager() {
String configPath = "file:home" + File.separator + "log4j.xml";
System.setProperty("log4j.configuration", configPath);
logger = Logger.getLogger(ApplicationManager.class);
}
protected void start() {
logger.info("*** Starting ApplicationManager ***");
}
when I run the application class the start method of the parent will be called, can it be called without calling the parent default constructor?
my second question is the above code different from this code:
public class Application extends ApplicationManager{
public static void main(String[] args) {
new Application().start();
}
#Override
protected void start() {
ProcessUtility.enableProcessUtility();
super.start();
}
}
and the ApplicationManager class as above.
this is the code of the static method:
public static void enableProcessUtility() {
isCommon = false;
}
thanks in advance.
Calling a non static method (your start method) requires creating an instance of the class that contains the method (or a sub-class of that class). Creating an instance of a class requires invoking the constructors of the class and all its ancestor classes. Therefore you can't avoid executing the parent default constructor.
As for the second question, moving ProcessUtility.enableProcessUtility() to the sub-class's start method means that it will be executed each time you call the start method.
That said, in your example your main only creates one instance of Application and only calls start once for that instance. Therefore ProcessUtility.enableProcessUtility() will only be executed once in both snippets, and the behavior would be identical.
EDIT: Another difference between the two snippets is that the first snippet calls ProcessUtility.enableProcessUtility() before creating the Application instance, while the second snippet first creates the instance and then calls ProcessUtility.enableProcessUtility() from within start of the sub-class. If the behavior of the constructors (of either the sub class or the super class) is affected by the call to ProcessUtility.enableProcessUtility(), the two snippets may produce different outputs.
Your first question is answered here https://stackoverflow.com/a/10508202/2527075
As for your second question, the super constructor will be called before the ProcessUtility call in the second example, where in the first example the ProcessUtility call comes first.
I have some code that I need to reuse in several Java apps. That code implements a GUI which in turn needs to access some static variables and methods from the calling class. Those variables and methods are always called the same in all of the apps. Is there a generic way to obtain a handle to the calling class in Java so the code for "someGUI" class can remain untouched and in fact come from the same source file for all the different apps?
Minimal working example:
import javax.swing.*;
class test {
static int variable = 123;
public static void main(String[] args) {
someGUI sg = new someGUI();
sg.setVisible(true);
}
}
class someGUI extends JFrame {
public someGUI() {
System.out.println(String.format("test.variable = %d", test.variable));
}
}
How can I "generify" the reference to "test" in test.variable to always just refer to the calling class? It's not the "super" class, at least using super.variable doesn't work.
Firstly I would advise against this approach since there are only brittle ways to implement it. You should parameterize SomeGUI with a parameter containing the values you need instead.
However, it is possible to do what you ask by examining the thread's stack trace and using reflection to access the static fields by name. For example like this:
class Test {
static int variable = 123;
public static void main(String[] args) throws Exception {
SomeGUI sg = new SomeGUI();
}
static class SomeGUI extends JFrame {
public SomeGUI() throws Exception {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
// stackTrace[0] is getStackTrace(), stackTrace[1] is SomeGUI(),
// stackTrace[2] is the point where our object is constructed.
StackTraceElement callingStackTraceElement = stackTrace[2];
String className = callingStackTraceElement.getClassName();
Class<?> c = Class.forName(className);
Field declaredField = c.getDeclaredField("variable");
Object value = declaredField.get(null);
System.out.println(String.format("test.variable = %d", value));
}
}
}
This will print test.variable = 123.
Obviously this is sensitive to renaming of the variables. It is also sensitive to dynamic proxies.
Also, it should be noted that you need to do this in the constructor. If you try to do this kind of lookup in other methods you can not find out how the instance was created.
There is no inheritance between somGUI and test,
Actual inheritance is there between someGUI and JFrame.
If you use super(), JVM tries to find 'variable' in JFrame, that is not what you wanted.
Use static methods setters & getters to access the 'variable' instead of direct accessing them.
Suppose the classes has code like this:
class C {
public static void show() {
}
}
class CTest {
public static void main (String[] args) {
C.show();
}
}
Then will it be perfectly legal to conclude that while referring to class C to access the static method show() here, behind the scene Java is actually calling the show() method through Java reflection ?
I.e. is it actually doing something like this
Class test = Class.forName(C);
test.show();
to call static methods?
If not, then how is it actually calling the static methods without creating objects?
If the above explanation is true, then how we'll justify the statement that "static members are only associated with classes, not objects" when we're actually invoking the method through a java.lang.Class object?
The JVM doesn't need to do anything like Class.forName() when calling a static method, because when the class that is calling the method is initialized (or when the method runs the first time, depending on where the static method call is), those other classes are looked up and a reference to the static method code is installed into the pool of data associated with that calling class. But at some point during that initialization, yes, the equivalent of Class.forName() is performed to find the other class.
This is a specious semantic argument. You could just as easily say that this reinforces the standard line that a static method is associated with the class rather than any instance of the class.
The JVM divides the memory it can use into different parts: one part where classes are stored, and one for the objects. (I think there might have been third part, but I am not quite sure about that right now).
Anyways, when an object is created, java looks up the corresponding class (like a blueprint) and creates a copy of it -> voila, we have an object. When a static method is called, the method of the class in the first part of the memory is executed, and not that of an object in the second part. (so there is no need to instantiate an object).
Besides, reflection needs a lot of resources, so using it to call static methods would considerably impact performance.
For extra info:
The called class will get loaded when it's first referenced by calling code.
i.e. The JVM only resolves and loads the class at the specific line of code that it first needs it.
You can verify this by using the JVM arg "-verbose:class" and stepping through with a debugger.
It will call ClassLoader.loadClass(String name) to load the class.
You can put a println statement into the ctor, to verify, whether it is called or not:
class C {
public static void show () {
System.out.println ("static: C.show ();");
}
public C () {
System.out.println ("C.ctor ();");
}
public void view () {
System.out.println ("c.view ();");
}
}
public class CTest
{
public static void main (String args[])
{
System.out.println ("static: ");
C.show ();
System.out.println ("object: ");
C c = new C ();
c.view ();
c.show (); // bad style, should be avoided
}
}
I was wondering what the effect of creating extra main methods would do to your code.
For example,
public class TestClass {
public static void main (String[] args){
TestClass foo = new TestClass();
}
}
After the program initially starts up, foo will be created and it would have another public main method inside it. Will that cause any errors?
It will cause no errors. Just because you initialize an object, doesn't mean the main method gets executed. Java will only initially call the main method of the class passed to it, like
>java TestClass
However, doing something like:
public class TestClass
{
public static void main (String[] args)
{
TestClass foo = new TestClass();
foo.main(args);
}
}
Or
public class TestClass
{
public TestClass()
{
//This gets executed when you create an instance of TestClass
main(null);
}
public static void main (String[] args)
{
TestClass foo = new TestClass();
}
}
That would cause a StackOverflowError, because you are explicitly calling TestClass's main method, which will then call the main method again, and again, and again, and....
When in doubt, just test it out :-)
The main method is static, which means it belongs to the class rather than the object. So the object won't have another main method inside it at all.
You could call the main method on instances of the object, but if you do that it's literally just another way of calling TestClass.main() (and it's frowned upon by many, including me, to call a static method on an instance of an object anyway.)
If you're referring to multiple main methods in the same program, then this isn't a problem either. The main class is simply specified and its main method is executed to start the program (in the case of a jar file this is the main-class attribute in the manifest file.)
It won't have an additional main-method, as main is static. So it's once per class.
If you have multiple main-methods in your project, you will specify which one to launch when starting your application.
This is perfectly fine. Having multiple main methods doesn't cause any problems. When you first start a Java program, execution begins in some function called main in a class specified by the user or by the .jar file. Once the program has started running, all the other functions called main are essentially ignored or treated like other functions.
After searching for a Java Class with multiple main() methods or in plain words, overloaded main() methods, I came up with an example of my own. Please have a look
public class MultipleMain{
public static void main(String args[]){
main(1);
main('c');
main("MyString");
}
public static void main(int i){
System.out.println("Inside Overloaded main()");
}
public static void main(char i){
System.out.println("Inside Overloaded main()");
}
public static void main(String str){
System.out.println("Inside Overloaded main()");
}
}
I tested this Java Code on JDK 1.7 and works like a charm !
You need "public static void main(String args[])" to start with and then you can call overloaded main methods inside this main and it should work for sure.
Any comments and suggestion are highly appreciated. I am just a novice Java Developer willing to develop my Java skills.
Thanks,
PK
No, you can have any number of main-methods in a project. Since you specify which one you want to use when you launch the program it doesn't cause any conflicts.
You can have only one main method in one class, But you can call one main method to the another explicitly
class Expmain
{
public static void main(String[] ar)
{
System.out.println("main 1");
}
}
class Expmain1
{
public static void main(String[] ar)
{
System.out.println("main 2");
Expmain.main(ar);
}
}
when you run your Java class it will always look for the signature public static void main(String args[]) in the class. So suppose if you invoking by command line argument, it will look for the method Signature in the class and will not invoke other until if u explicitly inoke it by its class name.
class MainMethod1{
public static void main(String[] ags){
System.out.println("Hi main 1");
testig2 y = new testig2();
//in this case MainMethod1 is invoked/.......
// String[] a = new String[10];
// testig2.main(a);
}
}
class MainMethod2{
public static void main(String[] ags){
System.out.println("Hi main 2");
}
}
But when you try the same from eclipse it will ask for which class to compile. Means MainMethod1 or Mainmethod2. So if te class has the exact signature they can be used as individual entry point to start the application.
Coming to your question, If you remove the signature as u did above by changing the argument if main method. It will act as a normal method.
It is all about the execution engine of JVM. Remember, you write >java com.abc.MainClass on cmd prompt.
It explains everything. If main method is not found here it throws a run time Error:Main Method Not Found in class MainClass.
Now if main method is found here, it acts as the first point when Program Counters have to map and start executing the instructions. Referred classes are loaded then, referred methods may be called using the instances created inside. So, main is class specific though one class can have only one main method.
Please note, main method's signature never changes. You can have two overloaded main methods in same class, like
public static void main(String[] args) {}
public static void main() {} //overloaded in same class.
During Static binding, the original main is resolved and identified by execution engine.
Another interesting point to consider is a case where you have two different classes in of java file.
For example, you have Java file with two classes:
public class FirstClassMultiply {
public static void main (String args[]){
System.out.println("Using FirstClassMultiply");
FirstClassMultiply mult = new FirstClassMultiply();
System.out.println("Multiple is :" + mult.multiply(2, 4));
}
public static void main (int i){
System.out.println("Using FirstClassMultiply with integer argument");
FirstClassMultiply mult = new FirstClassMultiply();
System.out.println("Multiply is :" + mult.multiply(2, 5));
}
int multiply(int a, int b) {
return (a * b);
}
}
class SecondClass {
public static void main(String args[]) {
System.out.println("Using SecondClass");
FirstClassMultiply mult = new FirstClassMultiply();
System.out.println("Multiply is :" + mult.multiply(2, 3));
FirstClassMultiply.main(null);
FirstClassMultiply.main(1);
}
}
Compiling it with javac FirstClassMultiply.java will generate two .class files, first one is FirstClassMultiply.class and second one is SecondClass.class
And in order to run it you will need to do it for the generated .class files: java FirstClassMultiply and java SecondClass, not the original filename file.
Please note a couple of additional points:
You will be able to run SecondClass.class although it's class wasn't public in the original file!
FirstClassMultiply overloading of the main method
of is totally fine, but, the only entry point to your prog
will be the main method with String args[] argument.
Example:
public class TestClass {
public static void main(String[] args) {
TestClass t = new TestClass();
}
private static void testMethod() {
abstract class TestMethod {
int a;
int b;
int c;
abstract void implementMe();
}
class DummyClass extends TestMethod {
void implementMe() {}
}
DummyClass dummy = new DummyClass();
}
}
I found out that the above piece of code is perfectly legal in Java. I have the following questions.
What is the use of ever having a class definition inside a method?
Will a class file be generated for DummyClass
It's hard for me to imagine this concept in an Object Oriented manner. Having a class definition inside a behavior. Probably can someone tell me with equivalent real world examples.
Abstract classes inside a method sounds a bit crazy to me. But no interfaces allowed. Is there any reason behind this?
This is called a local class.
2 is the easy one: yes, a class file will be generated.
1 and 3 are kind of the same question. You would use a local class where you never need to instantiate one or know about implementation details anywhere but in one method.
A typical use would be to create a throw-away implementation of some interface. For example you'll often see something like this:
//within some method
taskExecutor.execute( new Runnable() {
public void run() {
classWithMethodToFire.doSomething( parameter );
}
});
If you needed to create a bunch of these and do something with them, you might change this to
//within some method
class myFirstRunnableClass implements Runnable {
public void run() {
classWithMethodToFire.doSomething( parameter );
}
}
class mySecondRunnableClass implements Runnable {
public void run() {
classWithMethodToFire.doSomethingElse( parameter );
}
}
taskExecutor.execute(new myFirstRunnableClass());
taskExecutor.execute(new mySecondRunnableClass());
Regarding interfaces: I'm not sure if there's a technical issue that makes locally-defined interfaces a problem for the compiler, but even if there isn't, they wouldn't add any value. If a local class that implements a local interface were used outside the method, the interface would be meaningless. And if a local class was only going to be used inside the method, both the interface and the class would be implemented within that method, so the interface definition would be redundant.
Those are called local classes. You can find a detailed explanation and an example here. The example returns a specific implementation which we doesn't need to know about outside the method.
The class can't be seen (i.e. instantiated, its methods accessed without Reflection) from outside the method. Also, it can access the local variables defined in testMethod(), but before the class definition.
I actually thought: "No such file will be written." until I just tried it: Oh yes, such a file is created! It will be called something like A$1B.class, where A is the outer class, and B is the local class.
Especially for callback functions (event handlers in GUIs, like onClick() when a Button is clicked etc.), it's quite usual to use "anonymous classes" - first of all because you can end up with a lot of them. But sometimes anonymous classes aren't good enough - especially, you can't define a constructor on them. In these cases, these method local classes can be a good alternative.
The real purpose of this is to allow us to create classes inline in function calls to console those of us who like to pretend that we're writing in a functional language ;)
The only case when you would like to have a full blown function inner class vs anonymous class ( a.k.a. Java closure ) is when the following conditions are met
you need to supply an interface or abstract class implementation
you want to use some final parameters defined in calling function
you need to record some state of execution of the interface call.
E.g. somebody wants a Runnable and you want to record when the execution has started and ended.
With anonymous class it is not possible to do, with inner class you can do this.
Here is an example do demonstrate my point
private static void testMethod (
final Object param1,
final Object param2
)
{
class RunnableWithStartAndEnd extends Runnable{
Date start;
Date end;
public void run () {
start = new Date( );
try
{
evalParam1( param1 );
evalParam2( param2 );
...
}
finally
{
end = new Date( );
}
}
}
final RunnableWithStartAndEnd runnable = new RunnableWithStartAndEnd( );
final Thread thread = new Thread( runnable );
thread.start( );
thread.join( );
System.out.println( runnable.start );
System.out.println( runnable.end );
}
Before using this pattern though, please evaluate if plain old top-level class, or inner class, or static inner class are better alternatives.
The main reason to define inner classes (within a method or a class) is to deal with accessibility of members and variables of the enclosing class and method.
An inner class can look up private data members and operate on them. If within a method it can deal with final local variable as well.
Having inner classes does help in making sure this class is not accessible to outside world. This holds true especially for cases of UI programming in GWT or GXT etc where JS generating code is written in java and behavior for each button or event has to be defined by creating anonymous classes
I've came across a good example in the Spring. The framework is using concept of local class definitions inside of the method to deal with various database operations in a uniform way.
Assume you have a code like this:
JdbcTemplate jdbcOperations = new JdbcTemplate(this.myDataSource);
jdbcOperations.execute("call my_stored_procedure()")
jdbcOperations.query(queryToRun, new MyCustomRowMapper(), withInputParams);
jdbcOperations.update(queryToRun, withInputParams);
Let's first look at the implementation of the execute():
#Override
public void execute(final String sql) throws DataAccessException {
if (logger.isDebugEnabled()) {
logger.debug("Executing SQL statement [" + sql + "]");
}
/**
* Callback to execute the statement.
(can access method local state like sql input parameter)
*/
class ExecuteStatementCallback implements StatementCallback<Object>, SqlProvider {
#Override
#Nullable
public Object doInStatement(Statement stmt) throws SQLException {
stmt.execute(sql);
return null;
}
#Override
public String getSql() {
return sql;
}
}
//transforms method input into a functional Object
execute(new ExecuteStatementCallback());
}
Please note the last line. Spring does this exact "trick" for the rest of the methods as well:
//uses local class QueryStatementCallback implements StatementCallback<T>, SqlProvider
jdbcOperations.query(...)
//uses local class UpdateStatementCallback implements StatementCallback<Integer>, SqlProvider
jdbcOperations.update(...)
The "trick" with local classes allows the framework to deal with all of those scenarios in a single method which accept those classes via StatementCallback interface.
This single method acts as a bridge between actions (execute, update) and common operations around them (e.g execution, connection management, error translation and dbms console output)
public <T> T execute(StatementCallback<T> action) throws DataAccessException {
Assert.notNull(action, "Callback object must not be null");
Connection con = DataSourceUtils.getConnection(obtainDataSource());
Statement stmt = null;
try {
stmt = con.createStatement();
applyStatementSettings(stmt);
//
T result = action.doInStatement(stmt);
handleWarnings(stmt);
return result;
}
catch (SQLException ex) {
// Release Connection early, to avoid potential connection pool deadlock
// in the case when the exception translator hasn't been initialized yet.
String sql = getSql(action);
JdbcUtils.closeStatement(stmt);
stmt = null;
DataSourceUtils.releaseConnection(con, getDataSource());
con = null;
throw translateException("StatementCallback", sql, ex);
}
finally {
JdbcUtils.closeStatement(stmt);
DataSourceUtils.releaseConnection(con, getDataSource());
}
}
Everything is clear here but I wanted to place another example of reasonable use case for this definition type of class for the next readers.
Regarding #jacob-mattison 's answer, If we assume we have some common actions in these throw-away implementations of the interface, So, it's better to write it once but keep the implementations anonymous too:
//within some method
abstract class myRunnableClass implements Runnable {
protected abstract void DO_AN_SPECIFIC_JOB();
public void run() {
someCommonCode();
//...
DO_AN_SPECIFIC_JOB();
//..
anotherCommonCode();
}
}
Then it's easy to use this defined class and just implement the specific task separately:
taskExecutor.execute(new myRunnableClass() {
protected void DO_AN_SPECIFIC_JOB() {
// Do something
}
});
taskExecutor.execute(new myRunnableClass() {
protected void DO_AN_SPECIFIC_JOB() {
// Do another thing
}
});