1

Is there any way to force static initialization of some class B before entering the main() method of class A, without changing class A, using only VM options?

3
  • 1
    Explain better what you're trying to achieve. There's no VM option for that (what would be the use?) though. Commented Jan 6, 2014 at 14:32
  • I just wonder if there is a way to do so. Commented Jan 6, 2014 at 15:31
  • 3
    No, there's a reason why you wonder that. Tell us the reason. Commented Jan 6, 2014 at 16:03

2 Answers 2

1

I'm not aware of any way to do it without code. In code it's easy of course.

public class C {
   static {
      // Fetch and throw away an instance of B to make sure it is loaded
      B.getInstance();
   }

   static void main(String[] args) {
      // Do stuff, B is initialized
      A.main(args);
   }
}

In fact you could just do

public class C {
   static void main(String[] args) {
      B.getInstance();
      A.main(args);
   }
}

Your request doesn't make a lot of sense though. Ask a question about the problem you are trying to solve by doing this and you will hopefully get a much more useful answer.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for reply. I didn't consider the option to use other class so it might be helpful.
0

you could create a class that initializes other classes and then calls the real main method, e.g:

public static void main(String[] args) throws Exception {
    Class<?> mainClass = Class.forName(System.getProperty("mainClass"));

    for (String className : System.getProperty("initClasses").split(";")) {
        Class.forName(className);
    }

    Method main = mainClass.getMethod("main", String[].class);
    main.invoke(null, new Object[] { args });
}

Then you would start the application with that class as the main class and specify the real main class and the classes to be initialized via properties.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.