Solved

Invoke other method than main(String[])

Posted on 2002-05-02
8
217 Views
Last Modified: 2010-03-31
Hi!
If I specify to a java program a class to run it runs its "public static void main(String[])" method.
Is there a way to run other "public static void methodName(String[])" method?
Thanks!
0
Comment
Question by:rzvika2
8 Comments
 
LVL 7

Expert Comment

by:tomboshell
ID: 6988005
Yes.  What is the problem?  What error are you getting?  You want to make another static method that is public and takes a string arrray as a parameter.  Should be no problem.  Just make sure that the static works on static variables and methods (or a constructor), otherwise you will get an error saying that you are trying to access a non-static something within a static method.  

Tom
0
 
LVL 5

Expert Comment

by:Jan Louwerens
ID: 6988018
No, you can't run anything besides main with the 'java' command. But you can do something like:

public class Test
{
   public static void main(String args[])
   {
      Test test = new Test();
      test.run();
   }

   public void run()
   {
      System.out.println("Running...");
   }
}

This way, you can call any public function of the class, static or not.
0
 
LVL 7

Expert Comment

by:tomboshell
ID: 6988047
Oh, to 'run' it.  Sorry, I misunderstood/misread the question.
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 35

Expert Comment

by:girionis
ID: 6988106
 As jlouwere pointed you cannot run any other method with the "java" command besides the "main" mehtd. But I am just curious. Why would you want to do it?
0
 
LVL 92

Expert Comment

by:objects
ID: 6988198
This is a duplicate question.
0
 
LVL 4

Accepted Solution

by:
Neutron earned 100 total points
ID: 6988214
hi rzvika2 :-)

I'm also curious about the purpose, anyway here is one way to do it using reflection:

-------8<-------cut here---------------------invoke.java-------
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class invoke
{
    public static void main( String[] args ) throws Throwable
    {
        if (args.length < 2)
        {
            System.out.println( "\nUSAGE: invoke <class> <method> {parameters}\n" );
            System.exit( 7 );
        }
       
        String className = args[0];
        String methodName = args[1];
       
        Class clazz = Class.forName( className );
       
        Method method = null;
        Class[] methodParameters = { args.getClass() };
       
        while (method==null && clazz!=null)
        {
            try
            {
                method = clazz.getDeclaredMethod( methodName, methodParameters );
            }
            catch( Throwable t )
            {
            }
           
            if (method != null)
            {
                if (!Modifier.isAbstract( method.getModifiers() ))
                {
                    if (Modifier.isPublic( method.getModifiers() ))
                    {
                        if (!Modifier.isStatic( method.getModifiers() ))
                        {
                            System.out.println( "Method "+methodName+" declared in the class "+clazz.getName()+" is not static." );
                            System.exit( 77 );
                        }
                    }
                    else
                    {
                        System.out.println( "Method "+methodName+" declared in the class "+clazz.getName()+" is not public." );
                        System.exit( 777 );
                    }
                }
                else
                {
                    System.out.println( "Method "+methodName+" declared in the class "+clazz.getName()+" is abstract." );
                    System.exit( 7777 );
                }
            }
           
            if (method == null)
            {
                if (clazz != Object.class)
                {
                    clazz = clazz.getSuperclass();
                }
                else
                {
                    clazz = null;
                }
            }
        } // while
       
        if (method != null)
        {
            int rest = args.length-2;
            String[] restArgs = new String[Math.max( rest, 0 )];
           
            if (rest > 0)
            {
                System.arraycopy( args, 2, restArgs, 0, rest );
            }
           
            method.invoke( null, new Object[]{ restArgs } );
        }
    }
   
} /* invoke */
-------8<-------cut here---------------------invoke.java-------

-------8<-------cut here---------------------example.java-------
public class example
{
    public static void subsidiary( String[] args )
    {
        System.out.println( "H, W!" );
       
        for (int i=0; i<args.length; i++)
        {
            System.out.println( args[i] );
        }
    }
   
} /* example */
-------8<-------cut here---------------------example.java-------

Hopefully this is what you had in mind.
To run this you can use following cmd-line:

java invoke example subsidiary 1 2 3 4 5 6 7

...which should behave just as if you ran

java example 1 2 3 4 5 6 7

...having 'subsidiary' as the default application method.

Best wishes,
    </ntr> :)
0
 

Author Comment

by:rzvika2
ID: 6990820
Thanks for the effort !
(By the way, I need it for supplying some methods (to enter the java program from command line) in a specific class that do different things).
0
 
LVL 4

Expert Comment

by:Neutron
ID: 6993175
No problem :)
I hope that the duplicate question objects mentioned didn't have a reply similar to mine. If so, I would be glad to share the points :-)

Greetings,
    </ntr> :)
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
servlet example 11 49
maven module vs maven project 3 46
java imports not found 4 17
Notify sent to other threads in Java 9 33
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

792 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