Java ArgumentResolver Update
package de.hannespries.commons.cli;
import java.util.HashMap;
public class ArgumentResolver {
private HashMap<String, String> arguments = new HashMap<>();
public ArgumentResolver() {
}
public ArgumentResolver(String[] args) {
this.readArray(args);
}
/**
* converts an argument array with '-' as argument seperator in a easy
* readable structure
*
* @param args the argument array from e.g. the main-method
*/
public void addArray(String[] args){
this.readArray(args, false);
}
/**
* converts an argument array with '-' as argument seperator in a easy
* readable structure
*
* @param args the argument array from e.g. the main-method
*/
public void readArray(String[] args) {
this.readArray(args, true);
}
/**
* converts an argument array with '-' as argument seperator in a easy
* readable structure
*
* @param args the argument array from e.g. the main-method
* @param clearBefore clear the existing map
*/
public void readArray(String[] args, boolean clearBefore) {
if(clearBefore){
this.arguments.clear();
}
if (args != null && args.length > 0) {
String argName = "";
for (String arg : args) {
if (arg.startsWith("-")) {
argName = arg.substring(1, arg.length()).trim();
this.arguments.put(argName, "");
} else {
if (argName.trim().length() > 0) {
if (this.arguments.get(argName).trim().length() == 0) {
this.arguments.put(argName, this.arguments.get(argName).concat(arg));
} else {
this.arguments.put(argName, this.arguments.get(argName).concat(" " + arg));
}
}
}
}
}
}
/**
*
* @param name argument name
* @return gives back the existence of the argument with the given name
*/
public boolean existsIn(String name) {
return this.arguments.containsKey(name);
}
/**
*
* @param name argument name
* @param defaultValue argument value if not found
* @return value of the argument with the given name
*/
public String getArgumentValue(String name, String defaultValue) {
return this.existsIn(name) ? this.arguments.get(name).trim() : defaultValue;
}
/**
*
* @param name argument name
* @return value of the argument with the given name
*/
public String getArgumentValue(String name) {
return this.getArgumentValue(name, "");
}
/**
*
* @return count of arguments
*/
public int size() {
return this.arguments.size();
}
}
Syntax ist weiterhin so:
java -jar example.jar -name blubb blubb -value 1
name ist dann "blubb blubb" und value ist "1". Diese Klasse kommt an sich bei jeden meiner Java-Projekte zum Einsatz, wenn das Programm über die CLI bedient werden kann.