Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute main method inside inner class [duplicate]

How to execut main method, if it is present in static inner class?
Main method is present in static inner class and we need to execute that main method.

class A {
     static class B {
          public static void main(String[] args) {
             System.out.println("Done");
          }
     }
}
like image 345
Dinesh M Avatar asked Jul 10 '13 08:07

Dinesh M


2 Answers

Try something like this:

  java A$B

Update according to comments:

In linux shell you should escape $. So the command became:

java 'A$B'

like image 90
yatul Avatar answered Sep 28 '22 07:09

yatul


Its just like simple class. Run command java A$B When inner class is compiled, it is prepended with outer class name In this case you two class files. i.e . A.class and A$B.class

  • java command takes the classname as the argument and not the filename
  • So simple command java A$B will do the work
  • If you have anonymous classes then the classnames will be like OuterClass$1, OuterClass$1 and so on.

So if you modify your example as follows, now including anonymous and method local inner classes

import java.io.Serializable;

public class A {
    static class B {
        public static void main(String[] args) {
            System.out.println("Done");
            Serializable obj = new Serializable() {
            };
            Serializable obj1 = new Serializable() {
            };
            class MethodLocalClass {
            }                                           
        }
    }
}

Then the class files you will get are A.class, A$B.class, A$B$1.class, A$B$2.class for the anonymous classes and A$B$1MethodLocalClass.class.

Hope this example helps a bit :)

like image 44
Prasad Kharkar Avatar answered Sep 28 '22 08:09

Prasad Kharkar