There is no built-in way to do it.
That's why, for example, Guava provides a helper method for this task. Internally it's implemented as a simple mapping between primitives and wrappers.
Question
I know this question may seem silly because I could just do this manually. But I like to have all my options in one place (and one place only).
I want to set up the available options for a program (using commons-cli) by using the names of the fields in a dummy options class so that I can assign the values to an instance of that class.
The problem is that I can't figure out how to take the class object corresponding to a primitive type and retrieve the corresponding autobox class.
Here's the code I would like to have work (except that there's no such method getAutoboxClass)
public class PlayGame {
private static final Options opts = new Options();
static {
Field[] allOpts = MCTSOptions.class.getFields();
for (Field f : allOpts) {
opts.addOption(new Option(f.getName(), f.getName(), !f.getType()
.equals(Boolean.TYPE), f.getName()));
}
}
public static void main(String[] args) throws IOException, ParseException,
IllegalArgumentException, IllegalAccessException,
InvocationTargetException, SecurityException, NoSuchMethodException {
BasicParser bp = new BasicParser();
CommandLine cl = bp.parse(opts, args);
String[] remainArgs = cl.getArgs();
MCTSOptions params = new MCTSOptions();
for (Field f : MCTSOptions.class.getFields()) {
String name = f.getName();
if (f.getType().equals(Boolean.TYPE)) {
f.set(params, true);
} else if (f.getType().equals(String.class)) {
f.set(params, cl.getOptionValue(name));
} else {
String value = cl.getOptionValue(name);
Method m = f.getType().getAutoboxClass()
.getMethod("valueOf", String.class);
f.set(params, m.invoke(null, value));
}
}
}
//...
}
}
where MCTSOptions looks like:
public class MCTSOptions {
public boolean searchOnSample = false;
public double winOnlyMult = 0.5;
public double firstExplorationConstant = 2;
public double nextLearningRate = 0.1;
public double nextExplorationConstant = 2;
public boolean firstUsesSqrt = false;
public boolean nextUsesSqrt = false;
public long timeGiven = 5000L;
public long seed = 1L;
}
(so right now it's only longs and doubles, but in the future I might add other types)
Solution
There is no built-in way to do it.
That's why, for example, Guava provides a helper method for this task. Internally it's implemented as a simple mapping between primitives and wrappers.
OTHER TIPS
Why don't you just use the objects (Boolean, Long, etc) instead of the primitives?