Why can't ant start Main when the JVM can

class Main { public static void main(String[] args) { .... } } 

Running the program through the shell: java Main works as expected, but running the program through ant:

 <target name="run" depends="cmp"> <java classname="Main" classpath="."/> </target>` 

causes this error:

 java.lang.IllegalAccessException: Class org.apache.tools.ant.taskdefs.ExecuteJava can not access a member of class Main with modifiers "public static" 

JLS Section 12.3.3 Resolving symbolic links:

IllegalAccessError: there is a symbolic link that indicates the use or assignment of a field or the call to a method or the instantiation of the class to which the code contains the link does not have access, because the field or method was declared as private, protected or default access (not public) or because the class has not been declared public.

So, org.apache.tools.ant.taskdefs.ExecuteJava cannot execute the method, because it includes the class, it is private, but if I started jvm pointing to .class using a private method, it did not go through the same mechanism security?

This question , but I still do not understand

+7
source share
3 answers

The answer to this question is related to the question. When you run it through the JVM, it has access to everything, regardless of access level. When you run it through ant, which is another java program itself, it must obey the same rules as any other program, which means that it cannot see your main method.

If you declare your class as public class Main , the problem should go away.

As to why jvm made this decision to allow access to private classes at startup, this is a completely different matter. According to specification

12.1.4 Call Test.main

Finally, after the initialization for the Test class is completed (during which it may be associated with other subsequent loading, binding, and initialization), the main test method is called. The main method must be declared public, static, and invalid. It should take one argument; this is an array of strings. This method can be declared as

public static void main (String [] args) or public static void main (String ... args)

This specifically states that the method should be public , but does not say anything about the class in questions about why it works when calling main directly through the virtual machine.

+10
source

Try adding a public modifier to the class as follows:

 public class Main { public static void main(String[] args) { .... } } 
0
source

Use public access-modifier .

For example:

 public class Main { public static void main(String[] args) { // Your code.. } } 
0
source

All Articles