Question

argv[0] in Java (again)

Asked by: bcladd

Okay, in main (which is a static function) I would like to know the class used when java was run:

% java SomeMightyClass more and interesting parameters

The args array contains the more and interesting parameters but I don't have access to the string "SomeMightyClass".

Reason: I want to write a silly library that provides its own main function that instantiates an object of the given class (without requiring the client to write their own main). Started out as a simple exercise and now I am beating my head against this.

I know Class's getName method would work if I had an object of the approriate type...chicken needs an egg.
I can KNOW the class containing main (I am writing it). I can also get it from a stack trace...no additional information from the stack trace that I can find.
Reflection permits questions about an OBJECT's type to be asked and answered...chicken still needs an egg.

Okay, that summarizes what I know.

Thanks in advance for any assistance you can provide.
-bcl

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-06-22 at 12:13:08ID21034424
Tags

java

,

reflection

Topics

Java Programming Language

,

New to Java Programming

Participating Experts
6
Points
0
Comments
23

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. @ARGV on WinNT
    I've been using perl for a while on Unix and have just installed it on my WinNT machine. How do I get the script to access parameters from the command line? For example, I want to type: popup.pl *.html to run the script on all of the html files in the current directory....
  2. argv[0] For Winmain?
    Is it possible to obtain argv[0] information (program full path and name) using a win32 compiler such as Borland c++ 5? Winmain's lpCmdParam argument does not contain this info. Thanks.
  3. how can i get the length of argv[1] without strlen or loop…
    how can i get the length of argv[1] without strlen or looping
  4. argv question...
    I have a function: ParseArgs(int argc, char **argv); I want to feed a CString that is a return value from another function into the argv array, then call the function above. There would be a number of (say 50) different returned CStrings that argv points to and I need to a...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: x4uPosted on 2004-06-22 at 12:26:13ID: 11372919

The bad news is you cannot find the name of the class in which the main method is called from the args.
The good news is you can use "new Throwable().getStackTrace()[0].getClassName()" to get it. But this will show the class that really implements the main method, not the name of a subclass that might only inherit it.

 

by: sudhakar_koundinyaPosted on 2004-06-22 at 12:26:44ID: 11372923

Interesting Question. Would like to participate

 

by: x4uPosted on 2004-06-22 at 12:29:04ID: 11372947

If you find a better way to do this let me know. I'm looking for this since 1996. ;-)

 

by: GrandSchtroumpfPosted on 2004-06-22 at 12:37:51ID: 11373029

if you know the class, then why not using this to create your instance?
    MyClass.newInstance()

 

by: bcladdPosted on 2004-06-22 at 12:44:23ID: 11373103

Okay:

public class ApplicationFramework
{
    public void doTheRealWork() {}
    static public void main(String[] args) {
        // want to instantiate some subclass of ApplicationFramework
        // the name of which was supplied on the commandline as the executable
        // java class name; I don't know the class here
        ApplicationFramework app = new /*NameUnknown*/;
        app.doTheRealWork();
    }
}

public class MyApp
    extends ApplicationFramework
{
    public void doTheRealWork() {
        // something wonderful happens here (with very few lines of code)
    }
}

Want to run the program with the line:

% java MyApp

BUT main is defined in ApplicationFramework, not MyApp, so main does not know the class MyApp (though the JVM knew it to load it).

Hope this makes the problem clearer

 

by: x4uPosted on 2004-06-22 at 13:22:05ID: 11373523

You can't! Believe me, this is not worth to waste your time.
You may write your own native Java loader that passes the class name to the main method but there is no way to do this directly in Java.

 

by: x4uPosted on 2004-06-22 at 13:43:31ID: 11373762

I have a abstract class CmdLineTool that would need this as well. Here what I use to work around this:

public abstract class CmdLineTool
{
    protected static void runMain( CmdLineTool clt, String[] args )
    {
        try {
            clt.initCmdLineOptions();
            clt.processArgs( args );
            clt.execute();
        } catch( Throwable ex ) {
            clt.error( ex, null );
            System.exit( 1 );
        }
        System.exit( 0 );
    }
}

public class Converter extends CmdLineTool
{
    public static void main( String[] args )
    {
        runMain( new Converter(), args );
    }
}

 

by: objectsPosted on 2004-06-22 at 18:46:26ID: 11375512

> % java MyApp

What specific advantages does that give you over using:

% java ApplicationFramework MyApp

 

by: WebstormPosted on 2004-06-23 at 01:03:25ID: 11377039

Hi bcladd,

You just have to declare the doTheRealWork method as abstract:

public abstract class ApplicationFramework
{
    public abstract void doTheRealWork();
    static public void main(String[] args) {
        // want to instantiate some subclass of ApplicationFramework
        // the name of which was supplied on the commandline as the executable
        // java class name; I don't know the class here
        ApplicationFramework app = new /*NameUnknown*/;
        app.doTheRealWork(); // <-- will call MyApp without knowing the class name
    }
}

 

by: WebstormPosted on 2004-06-23 at 01:21:49ID: 11377125

forget my last comment.

 

by: GrandSchtroumpfPosted on 2004-06-23 at 02:29:47ID: 11377526

ok, i understand the problem now (the code you posted helped)...
but i still don't understand why you want to do that.
your "java" command argument is supposed to be the class that holds the main method, and not a child class.
as objects suggested, you can use this java command instead:
% java ApplicationFramework MyApp

...or just have classes that extend your ApplicationFramework provide their own main method ???

 

by: bcladdPosted on 2004-06-23 at 05:59:03ID: 11378700

Assume the framework is educational. I would like programs using the framework to run just like future programs NOT using the framework are run. I also want the framework-based programs to require as little code as possible; students should not need to write main for the first several labs.

GrandSchtroumpf - The java command argument is suppsed to be a class that HAS a main method (it MUST have one) so there is nothing wrong with using a class that extends a class with a main function.

I have a solution (I think) and will post more in a moment if posting works again.

-bcl

 

by: objectsPosted on 2004-06-23 at 15:36:23ID: 11384167

the method I suggested above meets all those criteria that I can tell, and requires no change to the framework-based programs.

 

by: bcladdPosted on 2004-06-30 at 11:07:06ID: 11438764

Sorry about the delay; I have been having problems filling out forms lately (don't know if the problem is on the wire or on the browser).

objects - Your proposal requires a change in command-line when NOT using the framework. This framework is educational and is supposed to support the student at the beginning but be light-weight enough that it can go away as the student learns enough Java. By providing my main() the student can focus on other methods and write an interactive program with little programming (and then the structure of a program can be exposed a little bit at a time over several programs).

-bcl

 

by: GrandSchtroumpfPosted on 2004-06-30 at 11:40:06ID: 11439106

> but be light-weight enough that it can go away as the student learns enough Java.
if the sudents' classes extend the framework it will be hard for it to go away.
anyway, the first thing you learn in java is to write a main method (with a sys.out that displays hello world).

 

by: objectsPosted on 2004-06-30 at 14:38:59ID: 11441224

> Your proposal requires a change in command-line when NOT using the framework.

Running *any* different app would require a change in the command line.
One could argue that the approach you are attempting would result in your students believing that they can run any Java class without having a main.

 

by: bcladdPosted on 2004-07-01 at 05:17:56ID: 11445796

(1)  One of the problems with Java as a first language is the amount of baggage that is required for something as simple as HelloWorld.java. The students must, at a minimum
  - Write the defintion of a class
  - Define a static method called main taking an array of String objects as a parameter
    - Students are not stupid; they don't like being forced to use magic incantations
    - Students are too inexperienced to use public static void main(String[] args) as anything BUT an incantation.
  - Ignore the arguments completely
  - Invoke a method on an object that is a member of an object passing a literal string as a parameter.
And when it is done they get a console application (I have had more than a few students in the past couple of years who didn't recognize what a console window is at first) that is not interactive at all.

Kim Bruce's work at Williams College using an events-first approach (an approach I toyed with back in graduate school but let slide) inspired me to provide a different introduciton to the language. Granted, class syntax is still necessary but if the methods overridden by the students are simple (void with no parameters for some, void with a single parameter for others), then the students' introduction to methods is gentler.

(2) The command-line changes to include the name of the class being executed, true, but the FORM of the command-line is not changed. That is, the number of parameters to the java virtual machine does not change and the meaning of each parameter doesn't change. There is some risk that students will think they can execute any class file in isolation (though not the same risk as using an IDE like BlueJ where in the IDE that is true). Two things will work against that: when they stop extending the framework they will be writing their own main method (later in their learning the idea of static will not be as scary and it will be a chance to introduce arrays and command-line parameters); if they "run" classes other than those that extend the framework the JVM will crash (and, one hopes, they will ask questions or read ahead).

-bcl

 

by: bcladdPosted on 2004-07-01 at 05:20:25ID: 11445814

By the way, using the ClassScope class over at JavaWorld () I found a solution to my particular problem:

  public static void main(String[] args) {
    Class[] allClasses
      = ClassScope.getLoadedClasses(ClassLoader.getSystemClassLoader());
    int i;
    Class applicationClass = null;
    Class frameworkClass = null;
    ApplicationFramework af = null;
   
    try {
      frameworkClass = Class.forName("ApplicationFramework");
    } catch (ClassNotFoundException e) {
    }

    try {
      for (i = 0; i < allClasses.length; ++i) {
        Object o = allClasses[i].newInstance();
        if ((o instanceof ApplicationFramework)
            && (allClasses[i] != simpleGameClass)) {
          applicationClass = allClasses[i];
          sg = (ApplicationFramework)o;
          break;
        }
      }
    } catch (InstantiationException iex) {
    } catch (IllegalAccessException iex) {
    }

    if (applicationClass != null) {
      af.doTheRealWork();        
    } else {
      System.err.println("No application found to match.");
    }
  }

-bcl

 

by: bcladdPosted on 2004-07-01 at 05:23:16ID: 11445834

Forgot to insert the JavaWorld link in the above: http://www.javaworld.com/javaworld/javaqa/2003-07/02-qa-0725-classsrc2.html

-bcl

 

by: x4uPosted on 2004-07-01 at 06:45:38ID: 11446610

PAQ and refund is ok for me.

bcladd, your solution looks promising although it's unfortunatly not an option in a real framework that has to work with more than one VM implementation.

If you want to hide as much as possible of the Java command line I think a single line batch file could fit even better because it can also hide other VM options that might be neccessary to run your framework.
runclass.bat:
  c:\j2se\bin\java.exe -mx... -cp ...;%~dp1 pkg.ApplicationFramework %~n1

(%~dp1 is used to append the path of the class to the classpath and %~n1 gives just the class name)

And it would allow your students to double click their class files if you register it for the .class extension:
C:\> ftype runclass=%SystemRoot%\runclass.bat "%1"
C:\> assoc .class=runclass

Although this would only work for classes that do not have a package.

 

by: objectsPosted on 2004-07-01 at 15:06:43ID: 11452246

If you are looking to ease use for your students then the following may be useful to you:

http://www.objects.com.au/products/jstart.do

 

by: moduloPosted on 2004-07-05 at 09:22:25ID: 11474125

Closed, 250 points refunded.

modulo
Community Support Moderator
Experts Exchange

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...