Solved

Invoke other method than main(String[])

Posted on 2002-05-02
8
212 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
 
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
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!

 
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

747 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

10 Experts available now in Live!

Get 1:1 Help Now