Solved

private static void main ?

Posted on 2000-05-18
5
358 Views
Last Modified: 2013-11-23
How does a main method work perfectly as a private function ?

Regards,
Ram
0
Comment
Question by:ramprasadr
5 Comments
 
LVL 3

Expert Comment

by:msmits
Comment Utility
Shouldn't be any problem, but you will not be able to start your application via that function.
When the virtual machine loads your class to execute as an application it will not find the main function in the external interface.
0
 
LVL 19

Accepted Solution

by:
Jim Cakalic earned 50 total points
Comment Utility
Well, according to the JVM specification, it shouldn't. But the JVM has intricate internal knowledge of all classes -- it has to. So the curent implementation of the JVM will find and invoke a private method main as long as it is static and its argument signature is correct. This is behavior that it is unwise to rely upon. The fact of Sun's own non-conforming JVM has been raised on the JDC forum and it is likely to change in the future.

Although I doubt that the JVM uses reflection to do this, in Java 2 it became possible for any class to see private members of other classes through reflection -- assuming that you have the security to do so. Using the invocation services offered by reflection, virtually anyone can call a private method on an object.

Best regards,
Jim Cakalic
0
 
LVL 7

Expert Comment

by:Ravindra76
Comment Utility

Hi JIM,

  Reflection package is listing only public methods.

0
 
LVL 19

Expert Comment

by:Jim Cakalic
Comment Utility
ravindra,

Prior to Java 1.2 you were correct. However, 1.2 added "reflective access control". The reflection Field, Method, and Constructor objects now extend AccessibleObject through which even private members may now be declared to be accessible. There is also a ReflectPermission class that will accomplish the same thing. Here is an example of it's use:

---------- ReflectObject.java ----------
import java.io.*;
import java.util.Vector;
import java.lang.reflect.*;

public class ReflectObject {
    private byte b = 1;
    private short sh = 2;
    private int i = 3;
    private long l = 4;
    private String s = "I'm a string";
    private char ch = 'c';
    private Vector v = new Vector();
    private Object[] a = new Object[2];

    public ReflectObject() {
        a[0] = new String("answer to life, the universe, and everything");
        a[1] = new Integer(42);
        v.add(a[0]);
        v.add(a[1]);
    }

    private static void writeObject(Writer w, Object o, String id) throws IOException {
        if (o == null) {
            w.write("null object encountered\n");
            return;
        }

        Class clazz = o.getClass();
        Field[] fields = clazz.getDeclaredFields();
        AccessibleObject.setAccessible(fields, true);
        String name = clazz.getName();

        w.write(clazz.getName() + " " + id +" = { ");
        for (int i = 0; i < fields.length; i++) {
            try {
                String fieldName = fields[i].getName();
                Class fieldClass = fields[i].getType();
                String fieldType = fieldClass.getName();
                String fieldValue;

                if (i > 0) {
                    w.write(", ");
                }
                if (fieldClass.isPrimitive()) {
                    if (fieldType.equals("int"))
                        fieldValue = String.valueOf(fields[i].getInt(o));
                    else if (fieldType.equals("short")) {
                        fieldValue = String.valueOf(fields[i].getShort(o));
                    } else if (fieldType.equals("boolean")) {
                        fieldValue = String.valueOf(fields[i].getBoolean(o));
                    } else if (fieldType.equals("char")) {
                        fieldValue = String.valueOf(fields[i].getChar(o));
                    } else if (fieldType.equals("byte")) {
                        fieldValue = String.valueOf(fields[i].getByte(o));
                    } else if (fieldType.equals("long")) {
                        fieldValue = String.valueOf(fields[i].getLong(o));
                    } else if (fieldType.equals("float")) {
                        fieldValue = String.valueOf(fields[i].getFloat(o));
                    } else if (fieldType.equals("double")) {
                        fieldValue = String.valueOf(fields[i].getDouble(o));
                    } else if (fieldType.equals("void")) {
                        fieldValue = new String("(void values unavailable)");
                    } else {
                        fieldValue = new String(" no value or type available ");
                    }
                    w.write(fieldName + "=" + fieldValue);
                } else if (fieldType.equalsIgnoreCase("java.lang.String")) {
                    w.write(fieldName + "='" + fields[i].get(o) + "'");
                } else {
                    // contained object
                    writeObject(w, fields[i].get(o), fieldName);
                }
            } catch (IllegalAccessException iae) {
                iae.printStackTrace();
                break;
            }
        }
        w.write(" }\n");
    }

    public static void write(Writer w, Object o, String id) {
        try {
            if (o == null) {
                w.write("null object supplied\n");
                return;
            }
            writeObject(w, o, id);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(0);
        }
    }

    public static void main(String[] args) {
        OutputStreamWriter w = new OutputStreamWriter(System.out);
        Object o = new ReflectObject();
        System.out.println(o);
        write(w, o, "o");
        try {
            w.flush();
        } catch (Exception e) {
        }
    }
}
---------- end ----------

Compile and invoke this on itself: "java ReflectObject ReflectObject" or any other class that contains private members. You will see that it is able to access private members of the class.

Best regards,
Jim Cakalic
0
 

Author Comment

by:ramprasadr
Comment Utility
Thank you very much, Jim. I was asked this question in an interview.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
This video teaches viewers about errors in exception handling.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now