JVM and private methods

I am new to Java. The first thing I learned was that the main () method of the executable class must be public , and the reason was that this method would be called by the JVM, it should be visible outside the class, and therefore should be public. Now, while studying serialization, I found that the private methods of the class writeObject()and readObject()class Serializablecan be called by the JVM when serializing and de-serializing an object! If they are private methods, then how can the JVM call them? If he can then why can't he call the main () method?

After going through some java documentation, I read this line: "The JVM can access the private methods of the object." Since we call readObject () with an instance of ObjectInputStream, therefore it is available to the JVM, whereas the main () method, which is a static or class method and called without instantiating any object of the class, must be publicly available to be accessible to the JVM! Does this make sense? I dont know.

+5
source share
2 answers

In general, I agree with @Christian, but I have two more notes:

  • The main () function may also be closed.

  • You can also call a private method / function if you really need to.

1 JVM main() . main(). , . , main() , , AFAIC. main() .

2 , Core Reflection API . :

      import java.lang.reflect.Field;
      class SimpleKeyPair {
         private String privateKey = "Cafe Babe"; // private field
      }
      public class PrivateMemberAccessTest {
        public static void main(String[] args) throws Exception {
          SimpleKeyPair keyPair = new SimpleKeyPair();
          Class c = keyPair.getClass();
          // get the reflected object 
          Field field = c.getDeclaredField("privateKey");
          // set accessible true 
          field.setAccessible(true);
          // prints "Cafe Babe"
          System.out.println("Value of privateKey: " + field.get(keyPair)); 
          // modify the member varaible
          field.set(keyPair, "Java Duke");
          // prints "Java Duke"
          System.out.println("Value of privateKey: " + field.get(keyPair)); 
        }
      }

http://www.jguru.com/faq/view.jsp?EID=321191

. fooobar.com/questions/18746/...

+2

. JVM - JVM, . JVM , . , JVM - , , - -.

writeObject . , . , JVM . , .

main() - , Java. , . JVM, , , JVM (!) (, ) .

+4

All Articles