001package org.kohsuke.args4j.util; 002 003import java.lang.reflect.Field; 004import java.util.ArrayList; 005import java.util.List; 006 007import org.kohsuke.args4j.Option; 008import org.kohsuke.args4j.ProxyOptionHandler; 009import org.kohsuke.args4j.spi.Getter; 010import org.kohsuke.args4j.spi.Getters; 011import org.openimaj.util.pair.IndependentPair; 012 013/** 014 * @author Sina Samangooei (ss@ecs.soton.ac.uk) 015 */ 016public class ArgsUtil { 017 018 private ArgsUtil() { 019 } 020 021 /** 022 * @param bean 023 * @return return the Args4j options which would result in the current bean 024 * @throws Exception 025 */ 026 public static String[] extractArguments(Object bean) throws Exception { 027 List<Getter<?>> arguments = null; 028 arguments = parse(bean); 029 List<String> args = new ArrayList<String>(); 030 for (Getter<?> optionHandler : arguments) { 031 List<IndependentPair<String, Class<?>>> values = optionHandler.getStringValues(); 032 for (IndependentPair<String, Class<?>> object : values) { 033 if(object.secondObject() == Boolean.class){ 034 if(object.firstObject() == null){ 035 continue; 036 } 037 else{ 038 args.add(optionHandler.getOptionName()); 039 } 040 } 041 else{ 042 args.add(optionHandler.getOptionName()); 043 args.add(object.firstObject()); 044 } 045 } 046 } 047 return args.toArray(new String[args.size()]); 048 } 049 050 private static List<Getter<?>> parse(Object bean) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { 051 ArrayList<Getter<?>> options = new ArrayList<Getter<?>>(); 052 // recursively process all the methods/fields. 053 for (Class<?> c = bean.getClass(); c != null; c = c.getSuperclass()) { 054 055 for (Field f : c.getDeclaredFields()) { 056 Option o = f.getAnnotation(Option.class); 057 if (o != null) { 058 options.add(Getters.create(o.name(),f, bean)); 059 if (o.handler() == ProxyOptionHandler.class) { 060 Field opField = c.getDeclaredField(f.getName() + "Op"); 061 Object opBean = null; 062 try{ 063 opBean = opField.get(bean); 064 } 065 catch (Exception e) { 066 opField.setAccessible(true); 067 opBean = opField.get(bean); 068 069 } 070 options.addAll(parse(opBean)); 071 } 072 } 073 } 074 } 075 return options; 076 } 077}