简体   繁体   中英

How do I code in java arguments into my main/constructors?

I have an executable

So the two constructors look like this:

public A()
{
//code
}

and

public A(String foo)
{
//more code here
}

The main looks like this:

A foo = new A();

Which of course, executes only the first constructor.

In B.jar, I'm calling it up like this:

rt.exec("java -jar pathToA.jar");

In another executable jar, called "B.jar", I would like to have the capability to execute A.jar using either constructor. How should I implement this? Should I get rid of the main method in my A.jar?

If you want to pass all args, I'd suggest keeping a constructor as:

A(String []args) {
}

and calling:

public static void main(String []args) {
 new A(args);
}

in the main function in the jar.

You can also chain the two constructors. See Constructor Chaining: http://www.javabeginner.com/learn-java/java-constructors

public A()
{
  this("default str", 0);
}

public A(String foo, int bar)
{
  // more code here
}

(I think that's better than String[] args, because you can easily mix up the order of the args, and also that way you could only handle Strings. (To handle different types you could use Object[] args, but that's even less maintainable since it's not even type safe.) And you want to keep the number of arguments under control.)

Note, that Usually someone want's to chain the other way, so the parameterized constructor would call the one with less parameters.

public A()
{
  // more code here
}

public A(String foo)
{
  this.setFoo(foo);
  // more code here
}

public A(String foo, int bar)
{
  this(foo);
  this.setBar(bar);
}

public A(String foo, int bar, float extra)
{
  this(foo, bar);
  this.setExtra(extra);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM