2013-04-09 25 views
0
获取autobox类

我知道这个问题可能看起来很愚蠢,因为我可以手动完成此操作。但我喜欢在一个地方拥有我的所有选项(仅限一个地方)。从类型

我想通过使用虚拟选项类中字段的名称来设置程序的可用选项(使用commons-cli),以便我可以将值分配给该类的实例。

问题是,我无法弄清楚如何获取对应于原始类型的类对象并检索相应的自动装箱类。

这是我想有工作(除非有没有这样的方法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)); 
       } 
      } 
     } 
     //... 
    } 
} 

其中MCTSOptions看起来像代码:

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; 
} 

(所以现在它只是多头和双打,但在未来我可能会添加其他类型)

+0

我不知道任何方法,但在Java中只有8种基元类型。你可以很容易地用一个开关或一系列if来实现这样的功能。 – ig0774 2013-04-09 20:12:25

+1

JDK中没有内置任何东西。 Guava有['Primitives.wrap(Class)'](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/primitives/Primitives.html#wrap(java .lang.Class)),但是。 – 2013-04-09 20:17:42

回答

1

有没有内置的方式来做到这一点。

这就是为什么,例如,番石榴为此任务提供a helper method。它在内部被实现为基元和包装之间的简单映射。

+0

谢谢。我在我的pom文件中添加了番石榴基元,并使用了Primitives.wrap – dspyz 2013-04-09 20:22:16

1

为什么不使用对象(布尔,长等)而不是基元?

+0

我可以。但我仍然认为可能有办法获得这些课程,我只是不知道。那将是我的第一选择。 – dspyz 2013-04-09 20:07:44