Example usage for java.lang Class getDeclaredConstructors

List of usage examples for java.lang Class getDeclaredConstructors

Introduction

In this page you can find the example usage for java.lang Class getDeclaredConstructors.

Prototype

@CallerSensitive
public Constructor<?>[] getDeclaredConstructors() throws SecurityException 

Source Link

Document

Returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object.

Usage

From source file:org.apache.axis.wsdl.fromJava.Emitter.java

/**
 * Sets the <code>Class</code> to export.
 * //from   w  w w  .j a v  a 2  s  . c  o  m
 * @param cls      the <code>Class</code> to export
 * @param location 
 */
public void setClsSmart(Class cls, String location) {

    if ((cls == null) || (location == null)) {
        return;
    }

    // Strip off \ and / from location
    if (location.lastIndexOf('/') > 0) {
        location = location.substring(location.lastIndexOf('/') + 1);
    } else if (location.lastIndexOf('\\') > 0) {
        location = location.substring(location.lastIndexOf('\\') + 1);
    }

    // Get the constructors of the class
    java.lang.reflect.Constructor[] constructors = cls.getDeclaredConstructors();
    Class intf = null;

    for (int i = 0; (i < constructors.length) && (intf == null); i++) {
        Class[] parms = constructors[i].getParameterTypes();

        // If the constructor has a single parameter
        // that is an interface which
        // matches the location, then use this as the interface class.
        if ((parms.length == 1) && parms[0].isInterface() && (parms[0].getName() != null)
                && Types.getLocalNameFromFullName(parms[0].getName()).equals(location)) {
            intf = parms[0];
        }
    }

    if (intf != null) {
        setCls(intf);

        if (implCls == null) {
            setImplCls(cls);
        }
    } else {
        setCls(cls);
    }
}

From source file:org.apache.hadoop.hive.ql.exec.vector.VectorizationContext.java

private Constructor<?> getConstructor(Class<?> cl) throws HiveException {
    try {//from   w w  w . j a  va  2s  .co m
        Constructor<?>[] ctors = cl.getDeclaredConstructors();
        if (ctors.length == 1) {
            return ctors[0];
        }
        Constructor<?> defaultCtor = cl.getConstructor();
        for (Constructor<?> ctor : ctors) {
            if (!ctor.equals(defaultCtor)) {
                return ctor;
            }
        }
        throw new HiveException("Only default constructor found");
    } catch (Exception ex) {
        throw new HiveException(ex);
    }
}

From source file:net.minecraftforge.common.util.EnumHelper.java

@SuppressWarnings({ "unchecked", "serial" })
@Nullable//from  w  w  w .  jav  a2s  . com
private static <T extends Enum<?>> T addEnum(boolean test, final Class<T> enumType, @Nullable String enumName,
        final Class<?>[] paramTypes, @Nullable Object[] paramValues) {
    if (!isSetup) {
        setup();
    }

    Field valuesField = null;
    Field[] fields = enumType.getDeclaredFields();

    for (Field field : fields) {
        String name = field.getName();
        if (name.equals("$VALUES") || name.equals("ENUM$VALUES")) //Added 'ENUM$VALUES' because Eclipse's internal compiler doesn't follow standards
        {
            valuesField = field;
            break;
        }
    }

    int flags = (FMLForgePlugin.RUNTIME_DEOBF ? Modifier.PUBLIC : Modifier.PRIVATE) | Modifier.STATIC
            | Modifier.FINAL | 0x1000 /*SYNTHETIC*/;
    if (valuesField == null) {
        String valueType = String.format("[L%s;", enumType.getName().replace('.', '/'));

        for (Field field : fields) {
            if ((field.getModifiers() & flags) == flags
                    && field.getType().getName().replace('.', '/').equals(valueType)) //Apparently some JVMs return .'s and some don't..
            {
                valuesField = field;
                break;
            }
        }
    }

    if (valuesField == null) {
        final List<String> lines = Lists.newArrayList();
        lines.add(String.format("Could not find $VALUES field for enum: %s", enumType.getName()));
        lines.add(String.format("Runtime Deobf: %s", FMLForgePlugin.RUNTIME_DEOBF));
        lines.add(String.format("Flags: %s",
                String.format("%16s", Integer.toBinaryString(flags)).replace(' ', '0')));
        lines.add("Fields:");
        for (Field field : fields) {
            String mods = String.format("%16s", Integer.toBinaryString(field.getModifiers())).replace(' ', '0');
            lines.add(String.format("       %s %s: %s", mods, field.getName(), field.getType().getName()));
        }

        for (String line : lines)
            FMLLog.log.fatal(line);

        if (test) {
            throw new EnhancedRuntimeException("Could not find $VALUES field for enum: " + enumType.getName()) {
                @Override
                protected void printStackTrace(WrappedPrintStream stream) {
                    for (String line : lines)
                        stream.println(line);
                }
            };
        }
        return null;
    }

    if (test) {
        Object ctr = null;
        Exception ex = null;
        try {
            ctr = getConstructorAccessor(enumType, paramTypes);
        } catch (Exception e) {
            ex = e;
        }
        if (ctr == null || ex != null) {
            throw new EnhancedRuntimeException(
                    String.format("Could not find constructor for Enum %s", enumType.getName()), ex) {
                private String toString(Class<?>[] cls) {
                    StringBuilder b = new StringBuilder();
                    for (int x = 0; x < cls.length; x++) {
                        b.append(cls[x].getName());
                        if (x != cls.length - 1)
                            b.append(", ");
                    }
                    return b.toString();
                }

                @Override
                protected void printStackTrace(WrappedPrintStream stream) {
                    stream.println("Target Arguments:");
                    stream.println("    java.lang.String, int, " + toString(paramTypes));
                    stream.println("Found Constructors:");
                    for (Constructor<?> ctr : enumType.getDeclaredConstructors()) {
                        stream.println("    " + toString(ctr.getParameterTypes()));
                    }
                }
            };
        }
        return null;
    }

    valuesField.setAccessible(true);

    try {
        T[] previousValues = (T[]) valuesField.get(enumType);
        T newValue = makeEnum(enumType, enumName, previousValues.length, paramTypes, paramValues);
        setFailsafeFieldValue(valuesField, null, ArrayUtils.add(previousValues, newValue));
        cleanEnumCache(enumType);

        return newValue;
    } catch (Exception e) {
        FMLLog.log.error("Error adding enum with EnumHelper.", e);
        throw new RuntimeException(e);
    }
}

From source file:com.parse.ParseObject.java

/**
 * Registers a custom subclass type with the Parse SDK, enabling strong-typing of those
 * {@code ParseObject}s whenever they appear. Subclasses must specify the {@link ParseClassName}
 * annotation and have a default constructor.
 *
 * @param subclass// ww w. ja  va2  s  .  c o m
 *          The subclass type to register.
 */
public static void registerSubclass(Class<? extends ParseObject> subclass) {
    String className = getClassName(subclass);
    if (className == null) {
        throw new IllegalArgumentException("No ParseClassName annotation provided on " + subclass);
    }
    if (subclass.getDeclaredConstructors().length > 0) {
        try {
            if (!isAccessible(subclass.getDeclaredConstructor())) {
                throw new IllegalArgumentException(
                        "Default constructor for " + subclass + " is not accessible.");
            }
        } catch (NoSuchMethodException e) {
            throw new IllegalArgumentException("No default constructor provided for " + subclass);
        }
    }
    Class<? extends ParseObject> oldValue = objectTypes.get(className);
    if (oldValue != null && subclass.isAssignableFrom(oldValue)) {
        // The old class was already more descendant than the new subclass type. No-op.
        return;
    }
    objectTypes.put(className, subclass);
    if (oldValue != null && !subclass.equals(oldValue)) {
        if (className.equals(getClassName(ParseUser.class))) {
            ParseUser.getCurrentUserController().clearFromMemory();
        } else if (className.equals(getClassName(ParseInstallation.class))) {
            ParseInstallation.getCurrentInstallationController().clearFromMemory();
        }
    }
}

From source file:com.basistech.rosette.apimodel.ModelTest.java

private Object createObjectForType(Class<?> type, Type genericParameterType)
        throws IllegalAccessException, InstantiationException, InvocationTargetException {
    Object o = null;/*from w  w  w  .  j  a  v a2 s .  com*/
    Class firstComponentType = type.isArray() ? type.getComponentType() : type;
    String typeName = firstComponentType.getSimpleName();
    Class parameterArgClass = null;
    Type[] parameterArgTypes = null;
    if (genericParameterType != null) {
        if (genericParameterType instanceof ParameterizedType) {
            ParameterizedType aType = (ParameterizedType) genericParameterType;
            parameterArgTypes = aType.getActualTypeArguments();
            for (Type parameterArgType : parameterArgTypes) {
                if (parameterArgType instanceof ParameterizedType) {
                    ParameterizedType parameterizedType = (ParameterizedType) parameterArgType;
                    if (isListString(parameterizedType)) {
                        List<List<String>> rv = Lists.newArrayList();
                        rv.add(Lists.newArrayList("string"));
                        return rv;
                    }
                } else {
                    parameterArgClass = (Class) parameterArgType;
                    if ("Map".equals(typeName)) {
                        break;
                    }
                }
            }
        }
    }
    if (firstComponentType.isEnum()) {
        return firstComponentType.getEnumConstants()[0];
    }
    switch (typeName) {
    case "byte": {
        if (type.isArray()) {
            o = "somebytes".getBytes();
        } else {
            o = (byte) '8';
        }
        break;
    }
    case "String":
    case "CharSequence": {
        o = "foo";
        break;
    }
    case "long":
    case "Long": {
        o = (long) 123456789;
        break;
    }
    case "Double":
    case "double": {
        o = 1.0;
        break;
    }
    case "int":
    case "Integer": {
        o = 98761234;
        break;
    }
    case "boolean":
    case "Boolean": {
        o = false;
        break;
    }

    case "Collection":
    case "List": {
        if (parameterArgClass != null) {
            Object o1 = createObjectForType(parameterArgClass, null);
            List<Object> list = new ArrayList<>();
            list.add(o1);
            o = list;
        }
        break;
    }
    case "Object":
        if (inputStreams) {
            o = new ByteArrayInputStream(new byte[0]);
        } else {
            o = "foo";
        }
        break;
    case "EnumSet":
        break;
    case "Set": {
        if (parameterArgClass != null) {
            Object o1 = createObjectForType(parameterArgClass, null);
            Set<Object> set = new HashSet<>();
            set.add(o1);
            o = set;
        }
        break;
    }
    case "Map": {
        if (parameterArgTypes != null && parameterArgTypes.length == 2) {
            Class keyClass = (Class) parameterArgTypes[0];
            Object keyObject = createObject(keyClass);
            if (keyObject != null) {
                HashMap<Object, Object> map = new HashMap<>();
                map.put(keyObject, null);
                o = map;
            }
        }
        break;
    }
    default:
        if (parameterArgClass != null) {
            Constructor[] ctors = parameterArgClass.getDeclaredConstructors();
            o = createObject(ctors[0]);
        } else {
            Constructor[] ctors = firstComponentType.getDeclaredConstructors();
            o = createObject(ctors[0]);
        }
    }
    return o;
}

From source file:org.openTwoFactor.client.util.TwoFactorClientCommonUtils.java

/**
 * Construct a class//ww w  .ja  va 2  s.com
 * @param <T> template type
 * @param theClass
 * @param allowPrivateConstructor true if should allow private constructors
 * @return the instance
 */
public static <T> T newInstance(Class<T> theClass, boolean allowPrivateConstructor) {
    if (!allowPrivateConstructor) {
        return newInstance(theClass);
    }
    try {
        Constructor<?>[] constructorArray = theClass.getDeclaredConstructors();
        for (Constructor<?> constructor : constructorArray) {
            if (constructor.getGenericParameterTypes().length == 0) {
                if (allowPrivateConstructor) {
                    constructor.setAccessible(true);
                }
                return (T) constructor.newInstance();
            }
        }
        //why cant we find a constructor???
        throw new RuntimeException("Why cant we find a constructor for class: " + theClass);
    } catch (Throwable e) {
        if (theClass != null && Modifier.isAbstract(theClass.getModifiers())) {
            throw new RuntimeException("Problem with class: " + theClass + ", maybe because it is abstract!",
                    e);
        }
        throw new RuntimeException("Problem with class: " + theClass, e);
    }
}

From source file:ca.oson.json.Oson.java

<T> T newInstance(Map<String, Object> map, Class<T> valueType) {
    InstanceCreator creator = getTypeAdapter(valueType);

    if (creator != null) {
        return (T) creator.createInstance(valueType);
    }//from w w w  .j a  v a2  s  .  c om

    T obj = null;

    if (valueType != null) {
        obj = (T) getDefaultValue(valueType);
        if (obj != null) {
            return obj;
        }
    }

    if (map == null) {
        return null;
    }

    // @JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS, include = As.PROPERTY, property = "@class")
    //@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = As.PROPERTY, property = "@class")
    String JsonClassType = null;

    if (valueType != null) {
        if (getAnnotationSupport()) {
            for (Annotation annotation : valueType.getAnnotations()) {
                if (annotation instanceof JsonTypeInfo) {
                    JsonTypeInfo jsonTypeInfo = (JsonTypeInfo) annotation;
                    JsonTypeInfo.Id use = jsonTypeInfo.use();
                    JsonTypeInfo.As as = jsonTypeInfo.include();
                    if ((use == JsonTypeInfo.Id.MINIMAL_CLASS || use == JsonTypeInfo.Id.CLASS)
                            && as == As.PROPERTY) {
                        JsonClassType = jsonTypeInfo.property();
                    }
                }
            }
        }
    }
    if (JsonClassType == null) {
        JsonClassType = getJsonClassType();
    }

    String className = null;
    if (map.containsKey(JsonClassType)) {
        className = map.get(JsonClassType).toString();
    }

    Class<T> classType = getClassType(className);

    //  && (valueType == null || valueType.isAssignableFrom(classType) || Map.class.isAssignableFrom(valueType))
    if (classType != null) {
        valueType = classType;
    }

    if (valueType == null) {
        return (T) map; // or null, which is better?
    }

    Constructor<?>[] constructors = null;

    Class implClass = null;
    if (valueType.isInterface() || Modifier.isAbstract(valueType.getModifiers())) {
        implClass = DeSerializerUtil.implementingClass(valueType.getName());
    }

    if (implClass != null) {
        constructors = implClass.getDeclaredConstructors();
    } else {
        constructors = valueType.getDeclaredConstructors();//.getConstructors();
    }

    Object singleMapValue = null;
    Class singleMapValueType = null;
    if (map.size() == 1) {
        singleMapValue = map.get(valueType.getName());

        if (singleMapValue != null) {
            singleMapValueType = singleMapValue.getClass();

            if (singleMapValueType == String.class) {
                singleMapValue = StringUtil.unquote(singleMapValue.toString(), isEscapeHtml());
            }

            try {
                if (valueType == Locale.class) {
                    Constructor constructor = null;
                    String[] parts = ((String) singleMapValue).split("_");
                    if (parts.length == 1) {
                        constructor = valueType.getConstructor(String.class);
                        constructor.setAccessible(true);
                        obj = (T) constructor.newInstance(singleMapValue);
                    } else if (parts.length == 2) {
                        constructor = valueType.getConstructor(String.class, String.class);
                        constructor.setAccessible(true);
                        obj = (T) constructor.newInstance(parts);
                    } else if (parts.length == 3) {
                        constructor = valueType.getConstructor(String.class, String.class, String.class);
                        constructor.setAccessible(true);
                        obj = (T) constructor.newInstance(parts);
                    }

                    if (obj != null) {
                        return obj;
                    }
                }
            } catch (Exception e) {
            }

            Map<Class, Constructor> cmaps = new HashMap<>();
            for (Constructor constructor : constructors) {
                //Class[] parameterTypes = constructor.getParameterTypes();

                int parameterCount = constructor.getParameterCount();
                if (parameterCount == 1) {

                    Class[] types = constructor.getParameterTypes();

                    cmaps.put(types[0], constructor);
                }
            }

            if (cmaps.size() > 0) {
                Constructor constructor = null;

                if ((cmaps.containsKey(Boolean.class) || cmaps.containsKey(boolean.class))
                        && BooleanUtil.isBoolean(singleMapValue.toString())) {
                    constructor = cmaps.get(Boolean.class);
                    if (constructor == null) {
                        constructor = cmaps.get(boolean.class);
                    }
                    if (constructor != null) {
                        try {
                            constructor.setAccessible(true);
                            obj = (T) constructor
                                    .newInstance(BooleanUtil.string2Boolean(singleMapValue.toString()));

                            if (obj != null) {
                                return obj;
                            }
                        } catch (Exception e) {
                        }
                    }

                } else if (StringUtil.isNumeric(singleMapValue.toString())) {

                    Class[] classes = new Class[] { int.class, Integer.class, long.class, Long.class,
                            double.class, Double.class, Byte.class, byte.class, Short.class, short.class,
                            Float.class, float.class, BigDecimal.class, BigInteger.class, AtomicInteger.class,
                            AtomicLong.class, Number.class };

                    for (Class cls : classes) {
                        constructor = cmaps.get(cls);

                        if (constructor != null) {
                            try {
                                obj = (T) constructor.newInstance(NumberUtil.getNumber(singleMapValue, cls));

                                if (obj != null) {
                                    return obj;
                                }
                            } catch (Exception e) {
                            }
                        }
                    }

                } else if (StringUtil.isArrayOrList(singleMapValue.toString())
                        || singleMapValue.getClass().isArray()
                        || Collection.class.isAssignableFrom(singleMapValue.getClass())) {
                    for (Entry<Class, Constructor> entry : cmaps.entrySet()) {
                        Class cls = entry.getKey();
                        constructor = entry.getValue();

                        if (cls.isArray() || Collection.class.isAssignableFrom(cls)) {
                            Object listObject = null;
                            if (singleMapValue instanceof String) {
                                JSONArray objArray = new JSONArray(singleMapValue.toString());
                                listObject = (List) fromJsonMap(objArray);
                            } else {
                                listObject = singleMapValue;
                            }

                            FieldData objectDTO = new FieldData(listObject, cls, true);
                            listObject = json2Object(objectDTO);
                            if (listObject != null) {
                                try {
                                    obj = (T) constructor.newInstance(listObject);
                                    if (obj != null) {
                                        return obj;
                                    }
                                } catch (Exception e) {
                                }
                            }
                        }

                    }

                }

                for (Entry<Class, Constructor> entry : cmaps.entrySet()) {
                    Class cls = entry.getKey();
                    constructor = entry.getValue();
                    try {
                        obj = (T) constructor.newInstance(singleMapValue);
                        if (obj != null) {
                            return obj;
                        }
                    } catch (Exception e) {
                    }
                }

            }

        }
    }

    if (implClass != null) {
        valueType = implClass;
    }

    try {
        obj = valueType.newInstance();

        if (obj != null) {
            return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType);
        }

    } catch (InstantiationException | IllegalAccessException e) {
        //e.printStackTrace();
    }

    ///*
    for (Constructor constructor : constructors) {
        //Class[] parameterTypes = constructor.getParameterTypes();

        int parameterCount = constructor.getParameterCount();
        if (parameterCount > 0) {
            constructor.setAccessible(true);

            Annotation[] annotations = constructor.getDeclaredAnnotations(); // getAnnotations();

            for (Annotation annotation : annotations) {
                boolean isJsonCreator = false;
                if (annotation instanceof JsonCreator) {
                    isJsonCreator = true;
                } else if (annotation instanceof ca.oson.json.annotation.FieldMapper) {
                    ca.oson.json.annotation.FieldMapper fieldMapper = (ca.oson.json.annotation.FieldMapper) annotation;

                    if (fieldMapper.jsonCreator() == BOOLEAN.TRUE) {
                        isJsonCreator = true;
                    }
                }

                if (isJsonCreator) {
                    Parameter[] parameters = constructor.getParameters();
                    String[] parameterNames = ObjectUtil.getParameterNames(parameters);

                    //parameterCount = parameters.length;
                    Object[] parameterValues = new Object[parameterCount];
                    int i = 0;
                    for (String parameterName : parameterNames) {
                        parameterValues[i] = getParameterValue(map, valueType, parameterName,
                                parameters[i].getType());
                        i++;
                    }

                    try {
                        obj = (T) constructor.newInstance(parameterValues);

                        if (obj != null) {
                            return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType);
                        }

                    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                            | InvocationTargetException e) {
                        //e.printStackTrace();
                    }
                }
            }

        } else {
            try {
                constructor.setAccessible(true);
                obj = (T) constructor.newInstance();

                if (obj != null) {
                    return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType);
                }

            } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                    | InvocationTargetException e) {
                //e.printStackTrace();
            }

        }
    }
    //*/

    // try again
    for (Constructor constructor : constructors) {
        int parameterCount = constructor.getParameterCount();
        if (parameterCount > 0) {
            constructor.setAccessible(true);

            try {
                List<String> parameterNames = ObjectUtil.getParameterNames(constructor);

                if (parameterNames != null && parameterNames.size() > 0) {
                    Class[] parameterTypes = constructor.getParameterTypes();

                    int length = parameterTypes.length;
                    if (length == parameterNames.size()) {
                        Object[] parameterValues = new Object[length];
                        Object parameterValue;
                        for (int i = 0; i < length; i++) {
                            parameterValues[i] = getParameterValue(map, valueType, parameterNames.get(i),
                                    parameterTypes[i]);
                        }

                        try {
                            obj = (T) constructor.newInstance(parameterValues);
                            if (obj != null) {
                                return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType);
                            }

                        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                                | InvocationTargetException e) {
                            //e.printStackTrace();
                        }

                    }
                }

            } catch (IOException e1) {
                // e1.printStackTrace();
            }
        }
    }

    // try more
    for (Constructor constructor : constructors) {
        int parameterCount = constructor.getParameterCount();
        if (parameterCount > 0) {
            constructor.setAccessible(true);

            Class[] parameterTypes = constructor.getParameterTypes();
            List<String> parameterNames;
            try {
                parameterNames = ObjectUtil.getParameterNames(constructor);

                if (parameterNames != null) {
                    int length = parameterTypes.length;

                    if (length > parameterNames.size()) {
                        length = parameterNames.size();
                    }

                    Object[] parameterValues = new Object[length];
                    for (int i = 0; i < length; i++) {
                        parameterValues[i] = getParameterValue(map, valueType, parameterNames.get(i),
                                parameterTypes[i]);
                    }

                    obj = (T) constructor.newInstance(parameterValues);
                    if (obj != null) {
                        return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType);
                    }
                }

            } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                    | InvocationTargetException | IOException e) {
                //e.printStackTrace();
            }
        }
    }

    // try more
    try {
        Method[] methods = valueType.getMethods(); // .getMethod("getInstance", null);

        List<Method> methodList = new ArrayList<>();

        if (methods != null) {
            for (Method method : methods) {
                String methodName = method.getName();

                if (methodName.equals("getInstance") || methodName.equals("newInstance")
                        || methodName.equals("createInstance") || methodName.equals("factory")) {
                    Class returnType = method.getReturnType();

                    if (valueType.isAssignableFrom(returnType) && Modifier.isStatic(method.getModifiers())) {
                        int parameterCount = method.getParameterCount();
                        if (parameterCount == 0) {
                            try {
                                obj = ObjectUtil.getMethodValue(null, method);
                                if (obj != null) {
                                    return setSingleMapValue(obj, valueType, singleMapValue,
                                            singleMapValueType);
                                }

                            } catch (IllegalArgumentException e) {
                                // TODO Auto-generated catch block
                                //e.printStackTrace();
                            }

                        } else {
                            methodList.add(method);
                        }

                    }
                }
            }

            for (Method method : methodList) {
                try {
                    int parameterCount = method.getParameterCount();
                    Object[] parameterValues = new Object[parameterCount];
                    Object parameterValue;
                    int i = 0;
                    Class[] parameterTypes = method.getParameterTypes();

                    String[] parameterNames = ObjectUtil.getParameterNames(method);

                    if (parameterCount == 1 && valueType != null && singleMapValue != null
                            && singleMapValueType != null) {

                        if (ObjectUtil.isSameDataType(parameterTypes[0], singleMapValueType)) {
                            try {
                                obj = ObjectUtil.getMethodValue(null, method, singleMapValue);
                                if (obj != null) {
                                    return obj;
                                }

                            } catch (IllegalArgumentException ex) {
                                //ex.printStackTrace();
                            }

                        }

                    } else if (parameterNames != null && parameterNames.length == parameterCount) {
                        for (String parameterName : ObjectUtil.getParameterNames(method)) {
                            parameterValues[i] = getParameterValue(map, valueType, parameterName,
                                    parameterTypes[i]);
                            i++;
                        }

                    } else {
                        // try annotation
                        Parameter[] parameters = method.getParameters();
                        parameterNames = ObjectUtil.getParameterNames(parameters);
                        parameterCount = parameters.length;
                        parameterValues = new Object[parameterCount];
                        i = 0;
                        for (String parameterName : parameterNames) {
                            parameterValues[i] = getParameterValue(map, valueType, parameterName,
                                    parameterTypes[i]);
                            i++;
                        }
                    }

                    obj = ObjectUtil.getMethodValue(null, method, parameterValues);

                    if (obj != null) {
                        return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType);
                    }

                } catch (IOException | IllegalArgumentException e) {
                    //e.printStackTrace();
                }
            }

        }

    } catch (SecurityException e) {
        // e.printStackTrace();
    }

    // try all static methods, if the return type is correct, get it as the final object
    Method[] methods = valueType.getDeclaredMethods();
    for (Method method : methods) {
        if (Modifier.isStatic(method.getModifiers())) {
            Class returnType = method.getReturnType();

            if (valueType.isAssignableFrom(returnType)) {
                try {
                    Object[] parameterValues = null;

                    int parameterCount = method.getParameterCount();
                    if (parameterCount > 0) {
                        if (parameterCount == 1 && map.size() == 1 && singleMapValue != null
                                && singleMapValueType != null) {
                            if (ObjectUtil.isSameDataType(method.getParameterTypes()[0], singleMapValueType)) {
                                obj = ObjectUtil.getMethodValue(null, method, singleMapValueType);
                                if (obj != null) {
                                    return obj;
                                }
                            }
                        }

                        parameterValues = new Object[parameterCount];
                        Object parameterValue;
                        int i = 0;
                        Class[] parameterTypes = method.getParameterTypes();

                        String[] parameterNames = ObjectUtil.getParameterNames(method);
                        if (parameterNames != null && parameterNames.length == parameterCount) {
                            for (String parameterName : ObjectUtil.getParameterNames(method)) {
                                parameterValues[i] = getParameterValue(map, valueType, parameterName,
                                        parameterTypes[i]);
                                i++;
                            }

                        } else {
                            // try annotation
                            Parameter[] parameters = method.getParameters();
                            parameterNames = ObjectUtil.getParameterNames(parameters);
                            parameterCount = parameters.length;
                            parameterValues = new Object[parameterCount];
                            i = 0;
                            for (String parameterName : parameterNames) {
                                parameterValues[i] = getParameterValue(map, valueType, parameterName,
                                        parameterTypes[i]);
                                i++;
                            }
                        }
                    }

                    obj = ObjectUtil.getMethodValue(obj, method, parameterValues);
                    if (obj != null) {
                        return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType);
                    }

                } catch (IOException | IllegalArgumentException e) {
                    //e.printStackTrace();
                }

            }
        }

    }

    return null;
}

From source file:org.dasein.persist.PersistentCache.java

@SuppressWarnings({ "rawtypes", "unchecked" })
protected Object mapValue(String fieldName, Object dataStoreValue, Class<?> toType, ParameterizedType ptype)
        throws PersistenceException {
    LookupDelegate delegate = getLookupDelegate(fieldName);

    if (dataStoreValue != null && delegate != null && !delegate.validate(dataStoreValue.toString())) {
        throw new PersistenceException("Value " + dataStoreValue + " for " + fieldName + " is not valid.");
    }// w  w  w  .  jav  a2 s  .  c  o  m
    try {
        if (toType.equals(String.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof String)) {
                dataStoreValue = dataStoreValue.toString();
            }
        } else if (Enum.class.isAssignableFrom(toType)) {
            if (dataStoreValue != null) {
                Enum e = Enum.valueOf((Class<? extends Enum>) toType, dataStoreValue.toString());

                dataStoreValue = e;
            }
        } else if (toType.equals(Boolean.class) || toType.equals(boolean.class)) {
            if (dataStoreValue == null) {
                dataStoreValue = false;
            } else if (!(dataStoreValue instanceof Boolean)) {
                if (Number.class.isAssignableFrom(dataStoreValue.getClass())) {
                    dataStoreValue = (((Number) dataStoreValue).intValue() != 0);
                } else {
                    dataStoreValue = (dataStoreValue.toString().trim().equalsIgnoreCase("true")
                            || dataStoreValue.toString().trim().equalsIgnoreCase("y"));
                }
            }
        } else if (Number.class.isAssignableFrom(toType) || toType.equals(byte.class)
                || toType.equals(short.class) || toType.equals(long.class) || toType.equals(int.class)
                || toType.equals(float.class) || toType.equals(double.class)) {
            if (dataStoreValue == null) {
                if (toType.equals(int.class) || toType.equals(short.class) || toType.equals(long.class)) {
                    dataStoreValue = 0;
                } else if (toType.equals(float.class) || toType.equals(double.class)) {
                    dataStoreValue = 0.0f;
                }
            } else if (toType.equals(Number.class)) {
                if (!(dataStoreValue instanceof Number)) {
                    if (dataStoreValue instanceof String) {
                        try {
                            dataStoreValue = Double.parseDouble((String) dataStoreValue);
                        } catch (NumberFormatException e) {
                            throw new PersistenceException("Unable to map " + fieldName + " as " + toType
                                    + " using " + dataStoreValue);
                        }
                    } else if (dataStoreValue instanceof Boolean) {
                        dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0);
                    } else {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                }
            } else if (toType.equals(Integer.class) || toType.equals(int.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Integer)) {
                        dataStoreValue = ((Number) dataStoreValue).intValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Integer.parseInt((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Long.class) || toType.equals(long.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Long)) {
                        dataStoreValue = ((Number) dataStoreValue).longValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Long.parseLong((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1L : 0L);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Byte.class) || toType.equals(byte.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Byte)) {
                        dataStoreValue = ((Number) dataStoreValue).byteValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Byte.parseByte((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Short.class) || toType.equals(short.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Short)) {
                        dataStoreValue = ((Number) dataStoreValue).shortValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Short.parseShort((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Double.class) || toType.equals(double.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Double)) {
                        dataStoreValue = ((Number) dataStoreValue).doubleValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Double.parseDouble((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1.0 : 0.0);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Float.class) || toType.equals(float.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Float)) {
                        dataStoreValue = ((Number) dataStoreValue).floatValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Float.parseFloat((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1.0f : 0.0f);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(BigDecimal.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof BigDecimal)) {
                        if (dataStoreValue instanceof BigInteger) {
                            dataStoreValue = new BigDecimal((BigInteger) dataStoreValue);
                        } else {
                            dataStoreValue = BigDecimal.valueOf(((Number) dataStoreValue).doubleValue());
                        }
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = new BigDecimal((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = new BigDecimal((((Boolean) dataStoreValue) ? 1.0 : 0.0));
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(BigInteger.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof BigInteger)) {
                        if (dataStoreValue instanceof BigDecimal) {
                            dataStoreValue = ((BigDecimal) dataStoreValue).toBigInteger();
                        } else {
                            dataStoreValue = BigInteger.valueOf(((Number) dataStoreValue).longValue());
                        }
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = new BigDecimal((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = new BigDecimal((((Boolean) dataStoreValue) ? 1.0 : 0.0));
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (dataStoreValue != null) {
                logger.error("Type of dataStoreValue=" + dataStoreValue.getClass());
                throw new PersistenceException(
                        "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
            }
        } else if (toType.equals(Locale.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof Locale)) {
                String[] parts = dataStoreValue.toString().split("_");

                if (parts != null && parts.length > 1) {
                    dataStoreValue = new Locale(parts[0], parts[1]);
                } else {
                    dataStoreValue = new Locale(parts[0]);
                }
            }
        } else if (Measured.class.isAssignableFrom(toType)) {
            if (dataStoreValue != null && ptype != null) {
                if (Number.class.isAssignableFrom(dataStoreValue.getClass())) {
                    Constructor<? extends Measured> constructor = null;
                    double value = ((Number) dataStoreValue).doubleValue();

                    for (Constructor<?> c : toType.getDeclaredConstructors()) {
                        Class[] args = c.getParameterTypes();

                        if (args != null && args.length == 2 && Number.class.isAssignableFrom(args[0])
                                && UnitOfMeasure.class.isAssignableFrom(args[1])) {
                            constructor = (Constructor<? extends Measured>) c;
                            break;
                        }
                    }
                    if (constructor == null) {
                        throw new PersistenceException("Unable to map with no proper constructor");
                    }
                    dataStoreValue = constructor.newInstance(value,
                            ((Class<?>) ptype.getActualTypeArguments()[0]).newInstance());
                } else if (!(dataStoreValue instanceof Measured)) {
                    try {
                        dataStoreValue = Double.parseDouble(dataStoreValue.toString());
                    } catch (NumberFormatException e) {
                        Method method = null;

                        for (Method m : toType.getDeclaredMethods()) {
                            if (Modifier.isStatic(m.getModifiers()) && m.getName().equals("valueOf")) {
                                if (m.getParameterTypes().length == 1
                                        && m.getParameterTypes()[0].equals(String.class)) {
                                    method = m;
                                    break;
                                }
                            }
                        }
                        if (method == null) {
                            throw new PersistenceException("Don't know how to map " + dataStoreValue + " to "
                                    + toType + "<" + ptype + ">");
                        }
                        dataStoreValue = method.invoke(null, dataStoreValue.toString());
                    }
                }
                // just because we converted it to a measured object above doesn't mean
                // we have the unit of measure right
                if (dataStoreValue instanceof Measured) {
                    UnitOfMeasure targetUom = (UnitOfMeasure) ((Class<?>) ptype.getActualTypeArguments()[0])
                            .newInstance();

                    if (!(((Measured) dataStoreValue).getUnitOfMeasure()).equals(targetUom)) {
                        dataStoreValue = ((Measured) dataStoreValue).convertTo(
                                (UnitOfMeasure) ((Class<?>) ptype.getActualTypeArguments()[0]).newInstance());
                    }
                }
            }
        } else if (toType.equals(UUID.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof UUID)) {
                dataStoreValue = UUID.fromString(dataStoreValue.toString());
            }
        } else if (toType.equals(TimeZone.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof TimeZone)) {
                dataStoreValue = TimeZone.getTimeZone(dataStoreValue.toString());
            }
        } else if (toType.equals(Currency.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof Currency)) {
                dataStoreValue = Currency.getInstance(dataStoreValue.toString());
            }
        } else if (toType.isArray()) {
            Class<?> t = toType.getComponentType();

            if (dataStoreValue == null) {
                dataStoreValue = Array.newInstance(t, 0);
            } else if (dataStoreValue instanceof JSONArray) {
                JSONArray arr = (JSONArray) dataStoreValue;

                if (long.class.isAssignableFrom(t)) {
                    long[] replacement = (long[]) Array.newInstance(long.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Long) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else if (int.class.isAssignableFrom(t)) {
                    int[] replacement = (int[]) Array.newInstance(int.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Integer) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else if (float.class.isAssignableFrom(t)) {
                    float[] replacement = (float[]) Array.newInstance(float.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Float) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else if (double.class.isAssignableFrom(t)) {
                    double[] replacement = (double[]) Array.newInstance(double.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Double) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else if (boolean.class.isAssignableFrom(t)) {
                    boolean[] replacement = (boolean[]) Array.newInstance(boolean.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Boolean) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else {
                    Object[] replacement = (Object[]) Array.newInstance(t, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                }
            } else if (!dataStoreValue.getClass().isArray()) {
                logger.error("Unable to map data store type " + dataStoreValue.getClass().getName() + " to "
                        + toType.getName());
                logger.error("Value of " + fieldName + "=" + dataStoreValue);
                throw new PersistenceException("Data store type=" + dataStoreValue.getClass().getName());
            }
        } else if (dataStoreValue != null && !toType.isAssignableFrom(dataStoreValue.getClass())) {
            Annotation[] alist = toType.getDeclaredAnnotations();
            boolean autoJSON = false;

            for (Annotation a : alist) {
                if (a instanceof AutoJSON) {
                    autoJSON = true;
                }
            }
            if (autoJSON) {
                dataStoreValue = autoDeJSON(toType, (JSONObject) dataStoreValue);
            } else {
                try {
                    Method m = toType.getDeclaredMethod("valueOf", JSONObject.class);

                    dataStoreValue = m.invoke(null, dataStoreValue);
                } catch (NoSuchMethodException ignore) {
                    try {
                        Method m = toType.getDeclaredMethod("valueOf", String.class);

                        if (m != null) {
                            dataStoreValue = m.invoke(null, dataStoreValue.toString());
                        } else {
                            throw new PersistenceException(
                                    "No valueOf() field in " + toType + " for mapping " + fieldName);
                        }
                    } catch (NoSuchMethodException e) {
                        throw new PersistenceException("No valueOf() field in " + toType + " for mapping "
                                + fieldName + " with " + dataStoreValue + ": ("
                                + dataStoreValue.getClass().getName() + " vs " + toType.getName() + ")");
                    }
                }
            }
        }
    } catch (Exception e) {
        String err = "Error mapping field in " + toType + " for " + fieldName + ": " + e.getMessage();
        logger.error(err, e);
        throw new PersistenceException();
    }
    return dataStoreValue;
}

From source file:com.github.wshackle.java4cpp.J4CppMain.java

public static void main(String[] args) throws IOException, ClassNotFoundException {
    main_completed = false;/*from   ww w.  j  ava 2s.  c o m*/

    Options options = new Options();
    options.addOption(Option.builder("?").desc("Print this message").longOpt("help").build());
    options.addOption(Option.builder("n").hasArg().desc("C++ namespace for newly generated classes.")
            .longOpt("namespace").build());
    options.addOption(
            Option.builder("c").hasArgs().desc("Single Java class to extract.").longOpt("classes").build());
    options.addOption(
            Option.builder("p").hasArgs().desc("Java Package prefix to extract").longOpt("packages").build());
    options.addOption(Option.builder("o").hasArg().desc("Output C++ source file.").longOpt("output").build());
    options.addOption(Option.builder("j").hasArg().desc("Input jar file").longOpt("jar").build());
    options.addOption(Option.builder("h").hasArg().desc("Output C++ header file.").longOpt("header").build());
    options.addOption(Option.builder("l").hasArg()
            .desc("Maximum limit on classes to extract from jars.[default=200]").longOpt("limit").build());
    options.addOption(Option.builder("v").desc("enable verbose output").longOpt("verbose").build());
    options.addOption(Option.builder().hasArg().desc("Classes per output file.[default=10]")
            .longOpt(CLASSESPEROUTPUT).build());
    options.addOption(Option.builder().hasArgs().desc(
            "Comma seperated list of nativeclass=javaclass native where nativeclass will be generated as an extension/implementation of the java class.")
            .longOpt("natives").build());
    options.addOption(Option.builder().hasArg()
            .desc("library name for System.loadLibrary(...) for native extension classes")
            .longOpt("loadlibname").build());
    String output = null;
    String header = null;
    String jar = null;
    Set<String> classnamesToFind = null;
    Set<String> packageprefixes = null;
    String loadlibname = null;

    Map<String, String> nativesNameMap = null;
    Map<String, Class> nativesClassMap = null;
    int limit = DEFAULT_LIMIT;
    int classes_per_file = 10;
    List<Class> classes = new ArrayList<>();

    String limitstring = Integer.toString(limit);

    try {
        // parse the command line arguments
        System.out.println("args = " + Arrays.toString(args));
        CommandLine line = new DefaultParser().parse(options, args);
        loadlibname = line.getOptionValue("loadlibname");
        verbose = line.hasOption("verbose");
        if (line.hasOption(CLASSESPEROUTPUT)) {
            String cpoStr = line.getOptionValue(CLASSESPEROUTPUT);
            try {
                int cpoI = Integer.valueOf(cpoStr);
                classes_per_file = cpoI;
            } catch (Exception e) {
                System.err.println("Option for " + CLASSESPEROUTPUT + "=\"" + cpoStr + "\"");
                printHelpAndExit(options, args);
            }
        }

        if (line.hasOption("natives")) {
            String natives[] = line.getOptionValues("natives");
            if (verbose) {
                System.out.println("natives = " + Arrays.toString(natives));
            }
            nativesNameMap = new HashMap<>();
            nativesClassMap = new HashMap<>();
            for (int i = 0; i < natives.length; i++) {
                int eq_index = natives[i].indexOf('=');
                String nativeClassName = natives[i].substring(0, eq_index).trim();
                String javaClassName = natives[i].substring(eq_index + 1).trim();
                Class javaClass = null;
                try {
                    javaClass = Class.forName(javaClassName);
                } catch (ClassNotFoundException e) {
                    //e.printStackTrace();
                    System.err.println("Class for " + javaClassName
                            + " not found. (It may be found later in jar if specified.)");
                }
                nativesNameMap.put(javaClassName, nativeClassName);
                if (javaClass != null) {
                    nativesClassMap.put(nativeClassName, javaClass);
                    if (!classes.contains(javaClass)) {
                        classes.add(javaClass);
                    }
                }
            }
        }
        //            // validate that block-size has been set
        //            if (line.hasOption("block-size")) {
        //                // print the value of block-size
        //                if(verbose) System.out.println(line.getOptionValue("block-size"));
        //            }
        jar = line.getOptionValue("jar", jar);
        if (verbose) {
            System.out.println("jar = " + jar);
        }
        if (null != jar) {
            if (jar.startsWith("~/")) {
                jar = new File(new File(getHomeDir()), jar.substring(2)).getCanonicalPath();
            }
            if (jar.startsWith("./")) {
                jar = new File(new File(getCurrentDir()), jar.substring(2)).getCanonicalPath();
            }
            if (jar.startsWith("../")) {
                jar = new File(new File(getCurrentDir()).getParentFile(), jar.substring(3)).getCanonicalPath();
            }
        }
        if (line.hasOption("classes")) {
            classnamesToFind = new HashSet<String>();
            String classStrings[] = line.getOptionValues("classes");
            if (verbose) {
                System.out.println("classStrings = " + Arrays.toString(classStrings));
            }
            classnamesToFind.addAll(Arrays.asList(classStrings));
            if (verbose) {
                System.out.println("classnamesToFind = " + classnamesToFind);
            }
        }
        //                if (!line.hasOption("namespace")) {
        //                    if (classname != null && classname.length() > 0) {
        //                        namespace = classname.toLowerCase().replace(".", "_");
        //                    } else if (jar != null && jar.length() > 0) {
        //                        int lastSep = jar.lastIndexOf(File.separator);
        //                        int start = Math.max(0, lastSep + 1);
        //                        int period = jar.indexOf('.', start + 1);
        //                        int end = Math.max(start + 1, period);
        //                        namespace = jar.substring(start, end).toLowerCase();
        //                        namespace = namespace.replace(" ", "_");
        //                        if (namespace.indexOf("-") > 0) {
        //                            namespace = namespace.substring(0, namespace.indexOf("-"));
        //                        }
        //                    }
        //                }

        namespace = line.getOptionValue("namespace", namespace);
        if (verbose) {
            System.out.println("namespace = " + namespace);
        }
        if (null != namespace) {
            output = namespace + ".cpp";
        }
        output = line.getOptionValue("output", output);
        if (verbose) {
            System.out.println("output = " + output);
        }
        if (null != output) {
            if (output.startsWith("~/")) {
                output = System.getProperty("user.home") + output.substring(1);
            }
            header = output.substring(0, output.lastIndexOf('.')) + ".h";
        } else {
            output = "out.cpp";
        }
        header = line.getOptionValue("header", header);
        if (verbose) {
            System.out.println("header = " + header);
        }
        if (null != header) {
            if (header.startsWith("~/")) {
                header = System.getProperty("user.home") + header.substring(1);
            }
        } else {
            header = "out.h";
        }

        if (line.hasOption("packages")) {
            packageprefixes = new HashSet<String>();
            packageprefixes.addAll(Arrays.asList(line.getOptionValues("packages")));
        }
        if (line.hasOption("limit")) {
            limitstring = line.getOptionValue("limit", Integer.toString(DEFAULT_LIMIT));
            limit = Integer.valueOf(limitstring);
        }
        if (line.hasOption("help")) {
            printHelpAndExit(options, args);
        }
    } catch (ParseException exp) {
        if (verbose) {
            System.out.println("Unexpected exception:" + exp.getMessage());
        }
        printHelpAndExit(options, args);
    }

    Set<Class> excludedClasses = new HashSet<>();
    Set<String> foundClassNames = new HashSet<>();
    excludedClasses.add(Object.class);
    excludedClasses.add(String.class);
    excludedClasses.add(void.class);
    excludedClasses.add(Void.class);
    excludedClasses.add(Class.class);
    excludedClasses.add(Enum.class);
    Set<String> packagesSet = new TreeSet<>();
    List<URL> urlsList = new ArrayList<>();
    String cp = System.getProperty("java.class.path");
    if (verbose) {
        System.out.println("System.getProperty(\"java.class.path\") = " + cp);
    }
    if (null != cp) {
        for (String cpe : cp.split(File.pathSeparator)) {
            if (verbose) {
                System.out.println("class path element = " + cpe);
            }
            File f = new File(cpe);
            if (f.isDirectory()) {
                urlsList.add(new URL("file:" + f.getCanonicalPath() + File.separator));
            } else if (cpe.endsWith(".jar")) {
                urlsList.add(new URL("jar:file:" + f.getCanonicalPath() + "!/"));
            }
        }
    }
    cp = System.getenv("CLASSPATH");
    if (verbose) {
        System.out.println("System.getenv(\"CLASSPATH\") = " + cp);
    }
    if (null != cp) {
        for (String cpe : cp.split(File.pathSeparator)) {
            if (verbose) {
                System.out.println("class path element = " + cpe);
            }
            File f = new File(cpe);
            if (f.isDirectory()) {
                urlsList.add(new URL("file:" + f.getCanonicalPath() + File.separator));
            } else if (cpe.endsWith(".jar")) {
                urlsList.add(new URL("jar:file:" + f.getCanonicalPath() + "!/"));
            }
        }
    }
    if (verbose) {
        System.out.println("urlsList = " + urlsList);
    }

    if (null != jar && jar.length() > 0) {
        Path jarPath = FileSystems.getDefault().getPath(jar);
        ZipInputStream zip = new ZipInputStream(Files.newInputStream(jarPath, StandardOpenOption.READ));

        URL jarUrl = new URL("jar:file:" + jarPath.toFile().getCanonicalPath() + "!/");
        urlsList.add(jarUrl);
        URL[] urls = urlsList.toArray(new URL[urlsList.size()]);
        if (verbose) {
            System.out.println("urls = " + Arrays.toString(urls));
        }
        URLClassLoader cl = URLClassLoader.newInstance(urls);
        for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
            // This ZipEntry represents a class. Now, what class does it represent?
            String entryName = entry.getName();
            if (verbose) {
                System.out.println("entryName = " + entryName);
            }

            if (!entry.isDirectory() && entryName.endsWith(".class")) {

                if (entryName.indexOf('$') >= 0) {
                    continue;
                }
                String classFileName = entry.getName().replace('/', '.');
                String className = classFileName.substring(0, classFileName.length() - ".class".length());
                if (classnamesToFind != null && classnamesToFind.size() > 0
                        && !classnamesToFind.contains(className)) {
                    if (verbose) {
                        System.out.println("skipping className=" + className + " because it does not found in="
                                + classnamesToFind);
                    }
                    continue;
                }
                try {
                    Class clss = cl.loadClass(className);
                    if (null != nativesClassMap && null != nativesNameMap
                            && nativesNameMap.containsKey(className)) {
                        nativesClassMap.put(nativesNameMap.get(className), clss);
                        if (!classes.contains(clss)) {
                            classes.add(clss);
                        }
                    }
                    if (packageprefixes != null && packageprefixes.size() > 0) {
                        if (null == clss.getPackage()) {
                            continue;
                        }
                        final String pkgName = clss.getPackage().getName();
                        boolean matchFound = false;
                        for (String prefix : packageprefixes) {
                            if (pkgName.startsWith(prefix)) {
                                matchFound = true;
                                break;
                            }
                        }
                        if (!matchFound) {
                            continue;
                        }
                    }
                    Package p = clss.getPackage();
                    if (null != p) {
                        packagesSet.add(clss.getPackage().getName());
                    }
                    if (!classes.contains(clss) && isAddableClass(clss, excludedClasses)) {
                        if (null != classnamesToFind && classnamesToFind.contains(className)
                                && !foundClassNames.contains(className)) {
                            foundClassNames.add(className);
                            if (verbose) {
                                System.out.println("foundClassNames = " + foundClassNames);
                            }
                        }
                        //                        if(verbose) System.out.println("clss = " + clss);
                        classes.add(clss);
                        //                        Class superClass = clss.getSuperclass();
                        //                        while (null != superClass
                        //                                && !classes.contains(superClass)
                        //                                && isAddableClass(superClass, excludedClasses)) {
                        //                            classes.add(superClass);
                        //                            superClass = superClass.getSuperclass();
                        //                        }
                    }
                } catch (ClassNotFoundException | NoClassDefFoundError ex) {
                    System.err.println(
                            "Caught " + ex.getClass().getName() + ":" + ex.getMessage() + " for className="
                                    + className + ", entryName=" + entryName + ", jarPath=" + jarPath);
                }
            }
        }
    }
    if (null != classnamesToFind) {
        if (verbose) {
            System.out.println("Checking classnames arguments");
        }
        for (String classname : classnamesToFind) {
            if (verbose) {
                System.out.println("classname = " + classname);
            }
            if (foundClassNames.contains(classname)) {
                if (verbose) {
                    System.out.println("foundClassNames.contains(" + classname + ")");
                }
                continue;
            }
            try {
                if (classes.contains(Class.forName(classname))) {
                    if (verbose) {
                        System.out.println("Classes list already contains:  " + classname);
                    }
                    continue;
                }
            } catch (Exception e) {

            }

            if (null != classname && classname.length() > 0) {
                urlsList.add(new URL("file://" + System.getProperty("user.dir") + "/"));

                URL[] urls = urlsList.toArray(new URL[urlsList.size()]);
                if (verbose) {
                    System.out.println("urls = " + Arrays.toString(urls));
                }
                URLClassLoader cl = URLClassLoader.newInstance(urls);
                Class c = null;
                try {
                    c = cl.loadClass(classname);
                } catch (ClassNotFoundException e) {
                    System.err.println("Class " + classname + " not found ");
                }
                if (verbose) {
                    System.out.println("c = " + c);
                }
                if (null == c) {
                    try {
                        c = ClassLoader.getSystemClassLoader().loadClass(classname);
                    } catch (ClassNotFoundException e) {
                        if (verbose) {
                            System.out.println("System ClassLoader failed to find " + classname);
                        }
                    }
                }
                if (null != c) {
                    classes.add(c);
                } else {
                    System.err.println("Class " + classname + " not found");
                }
            }
        }
        if (verbose) {
            System.out.println("Finished checking classnames arguments");
        }
    }
    if (classes == null || classes.size() < 1) {
        if (null == nativesClassMap || nativesClassMap.keySet().size() < 1) {
            System.err.println("No Classes specified or found.");
            System.exit(1);
        }
    }
    if (verbose) {
        System.out.println("Classes found = " + classes.size());
    }
    if (classes.size() > limit) {
        System.err.println("limit=" + limit);
        System.err.println(
                "Too many classes please use -c or -p options to limit classes or -l to increase limit.");
        if (verbose) {
            System.out.println("packagesSet = " + packagesSet);
        }
        System.exit(1);
    }
    List<Class> newClasses = new ArrayList<Class>();
    for (Class clss : classes) {
        Class superClass = clss.getSuperclass();
        while (null != superClass && !classes.contains(superClass) && !newClasses.contains(superClass)
                && isAddableClass(superClass, excludedClasses)) {
            newClasses.add(superClass);
            superClass = superClass.getSuperclass();
        }
        try {
            Field fa[] = clss.getDeclaredFields();
            for (Field f : fa) {
                if (Modifier.isPublic(f.getModifiers())) {
                    Class fClass = f.getType();
                    if (!classes.contains(fClass) && !newClasses.contains(fClass)
                            && isAddableClass(fClass, excludedClasses)) {
                        newClasses.add(fClass);
                    }
                }
            }
        } catch (NoClassDefFoundError e) {
            e.printStackTrace();
        }
        for (Method m : clss.getDeclaredMethods()) {
            if (m.isSynthetic()) {
                continue;
            }
            if (!Modifier.isPublic(m.getModifiers()) || Modifier.isAbstract(m.getModifiers())) {
                continue;
            }
            Class retType = m.getReturnType();
            if (verbose) {
                System.out.println("Checking dependancies for Method = " + m);
            }
            if (!classes.contains(retType) && !newClasses.contains(retType)
                    && isAddableClass(retType, excludedClasses)) {
                newClasses.add(retType);
                superClass = retType.getSuperclass();
                while (null != superClass && !classes.contains(superClass) && !newClasses.contains(superClass)
                        && isAddableClass(superClass, excludedClasses)) {
                    newClasses.add(superClass);
                    superClass = superClass.getSuperclass();
                }
            }
            for (Class paramType : m.getParameterTypes()) {
                if (!classes.contains(paramType) && !newClasses.contains(paramType)
                        && isAddableClass(paramType, excludedClasses)) {
                    newClasses.add(paramType);
                    superClass = paramType.getSuperclass();
                    while (null != superClass && !classes.contains(superClass)
                            && !newClasses.contains(superClass) && !excludedClasses.contains(superClass)) {
                        newClasses.add(superClass);
                        superClass = superClass.getSuperclass();
                    }
                }
            }
        }
    }
    if (null != nativesClassMap) {
        for (Class clss : nativesClassMap.values()) {
            if (null != clss) {
                Class superClass = clss.getSuperclass();
                while (null != superClass && !classes.contains(superClass) && !newClasses.contains(superClass)
                        && !excludedClasses.contains(superClass)) {
                    newClasses.add(superClass);
                    superClass = superClass.getSuperclass();
                }
            }
        }
    }
    if (verbose) {
        System.out.println("Dependency classes needed = " + newClasses.size());
    }
    classes.addAll(newClasses);
    List<Class> newOrderClasses = new ArrayList<>();
    for (Class clss : classes) {
        if (newOrderClasses.contains(clss)) {
            continue;
        }
        Class superClass = clss.getSuperclass();
        Stack<Class> stack = new Stack<>();
        while (null != superClass && !newOrderClasses.contains(superClass)
                && !superClass.equals(java.lang.Object.class)) {
            stack.push(superClass);
            superClass = superClass.getSuperclass();
        }
        while (!stack.empty()) {
            newOrderClasses.add(stack.pop());
        }
        newOrderClasses.add(clss);
    }
    classes = newOrderClasses;
    if (verbose) {
        System.out.println("Total number of classes = " + classes.size());
        System.out.println("classes = " + classes);
    }

    String forward_header = header.substring(0, header.lastIndexOf('.')) + "_fwd.h";
    Map<String, String> map = new HashMap<>();
    map.put(JAR, jar != null ? jar : "");
    map.put("%CLASSPATH_PREFIX%",
            getCurrentDir() + ((jar != null)
                    ? (File.pathSeparator + ((new File(jar).getCanonicalPath()).replace("\\", "\\\\")))
                    : ""));
    map.put("%FORWARD_HEADER%", forward_header);
    map.put("%HEADER%", header);
    map.put("%PATH_SEPERATOR%", File.pathSeparator);
    String tabs = "";
    String headerDefine = forward_header.substring(Math.max(0, forward_header.indexOf(File.separator)))
            .replace(".", "_");
    map.put(HEADER_DEFINE, headerDefine);
    map.put(NAMESPACE, namespace);
    if (null != nativesClassMap) {
        for (Entry<String, Class> e : nativesClassMap.entrySet()) {
            final Class javaClass = e.getValue();
            final String nativeClassName = e.getKey();
            try (PrintWriter pw = new PrintWriter(new FileWriter(nativeClassName + ".java"))) {
                if (javaClass.isInterface()) {
                    pw.println("public class " + nativeClassName + " implements " + javaClass.getCanonicalName()
                            + ", AutoCloseable{");
                } else {
                    pw.println("public class " + nativeClassName + " extends " + javaClass.getCanonicalName()
                            + " implements AutoCloseable{");
                }
                if (null != loadlibname && loadlibname.length() > 0) {
                    pw.println(TAB_STRING + "static {");
                    pw.println(TAB_STRING + TAB_STRING + "System.loadLibrary(\"" + loadlibname + "\");");
                    pw.println(TAB_STRING + "}");
                    pw.println();
                }
                pw.println(TAB_STRING + "public " + nativeClassName + "() {");
                pw.println(TAB_STRING + "}");
                pw.println();
                pw.println(TAB_STRING + "private long nativeAddress=0;");
                pw.println(TAB_STRING + "private boolean nativeDeleteOnClose=false;");
                pw.println();

                pw.println(TAB_STRING + "protected " + nativeClassName + "(final long nativeAddress) {");
                pw.println(TAB_STRING + TAB_STRING + "this.nativeAddress = nativeAddress;");
                pw.println(TAB_STRING + "}");

                pw.println(TAB_STRING + "private native void nativeDelete();");
                pw.println();
                pw.println(TAB_STRING + "@Override");
                pw.println(TAB_STRING + "public synchronized void  close() {");
                //                        pw.println(TAB_STRING + TAB_STRING + "if(nativeAddress != 0 && nativeDeleteOnClose) {");
                pw.println(TAB_STRING + TAB_STRING + "nativeDelete();");
                //                        pw.println(TAB_STRING + TAB_STRING + "}");
                //                        pw.println(TAB_STRING + TAB_STRING + "nativeAddress=0;");
                //                        pw.println(TAB_STRING + TAB_STRING + "nativeDeleteOnClose=false;");
                pw.println(TAB_STRING + "}");

                pw.println();
                pw.println(TAB_STRING + "protected void finalizer() {");
                pw.println(TAB_STRING + TAB_STRING + "close();");
                pw.println(TAB_STRING + "}");

                pw.println();
                Method ma[] = javaClass.getDeclaredMethods();
                for (Method m : ma) {
                    int modifiers = m.getModifiers();
                    if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers)
                            && !Modifier.isStatic(modifiers)
                            //                                && !m.isDefault()
                            && !m.isSynthetic()) {
                        pw.println();
                        pw.println(TAB_STRING + "@Override");
                        String params = "";
                        for (int i = 0; i < m.getParameterTypes().length; i++) {
                            params += m.getParameterTypes()[i].getCanonicalName() + " param" + i;
                            if (i < m.getParameterTypes().length - 1) {
                                params += ",";
                            }
                        }
                        pw.println(TAB_STRING + "native public " + m.getReturnType().getCanonicalName() + " "
                                + m.getName() + "(" + params + ");");
                        //                                    + IntStream.range(0, m.getParameterTypes().length)
                        //                                    .mapToObj(i -> m.getParameterTypes()[i].getCanonicalName() + " param" + i)
                        //                                    .collect(Collectors.joining(",")) + ");");
                    }
                }
                pw.println("}");
            }
        }
    }
    try (PrintWriter pw = new PrintWriter(new FileWriter(forward_header))) {
        tabs = "";
        processTemplate(pw, map, "header_fwd_template_start.h", tabs);
        Class lastClass = null;
        for (int class_index = 0; class_index < classes.size(); class_index++) {
            Class clss = classes.get(class_index);
            String clssOnlyName = getCppClassName(clss);
            tabs = openClassNamespace(clss, pw, tabs, lastClass);
            tabs += TAB_STRING;
            pw.println(tabs + "class " + clssOnlyName + ";");
            tabs = tabs.substring(0, tabs.length() - 1);
            Class nextClass = (class_index < (classes.size() - 1)) ? classes.get(class_index + 1) : null;
            tabs = closeClassNamespace(clss, pw, tabs, nextClass);
            lastClass = clss;
        }
        processTemplate(pw, map, "header_fwd_template_end.h", tabs);
    }
    headerDefine = header.substring(Math.max(0, header.indexOf(File.separator))).replace(".", "_");
    map.put(HEADER_DEFINE, headerDefine);
    map.put(NAMESPACE, namespace);
    if (classes_per_file < 1) {
        classes_per_file = classes.size();
    }
    final int num_class_segments = (classes.size() > 1)
            ? ((classes.size() + classes_per_file - 1) / classes_per_file)
            : 1;
    String fmt = "%d";
    if (num_class_segments > 10) {
        fmt = "%02d";
    }
    if (num_class_segments > 100) {
        fmt = "%03d";
    }
    String header_file_base = header;
    if (header_file_base.endsWith(".h")) {
        header_file_base = header_file_base.substring(0, header_file_base.length() - 2);
    } else if (header_file_base.endsWith(".hh")) {
        header_file_base = header_file_base.substring(0, header_file_base.length() - 3);
    } else if (header_file_base.endsWith(".hpp")) {
        header_file_base = header_file_base.substring(0, header_file_base.length() - 4);
    }
    try (PrintWriter pw = new PrintWriter(new FileWriter(header))) {
        tabs = "";
        processTemplate(pw, map, HEADER_TEMPLATE_STARTH, tabs);
        for (int segment_index = 0; segment_index < num_class_segments; segment_index++) {
            String header_segment_file = header_file_base + String.format(fmt, segment_index) + ".h";
            pw.println("#include \"" + header_segment_file + "\"");
        }
        if (null != nativesClassMap) {
            tabs = TAB_STRING;
            for (Entry<String, Class> e : nativesClassMap.entrySet()) {
                final Class javaClass = e.getValue();
                final String nativeClassName = e.getKey();
                pw.println();
                pw.println(tabs + "class " + nativeClassName + "Context;");
                pw.println();
                map.put(CLASS_NAME, nativeClassName);
                map.put("%BASE_CLASS_FULL_NAME%",
                        "::" + namespace + "::" + getModifiedClassName(javaClass).replace(".", "::"));
                map.put(OBJECT_CLASS_FULL_NAME, "::" + namespace + "::java::lang::Object");
                processTemplate(pw, map, HEADER_CLASS_STARTH, tabs);
                tabs += TAB_STRING;
                pw.println(tabs + nativeClassName + "Context *context;");
                pw.println(tabs + nativeClassName + "();");
                pw.println(tabs + "~" + nativeClassName + "();");
                Method methods[] = javaClass.getDeclaredMethods();
                for (int j = 0; j < methods.length; j++) {
                    Method method = methods[j];
                    int modifiers = method.getModifiers();
                    if (!Modifier.isPublic(modifiers)) {
                        continue;
                    }
                    if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers)
                            && !Modifier.isStatic(modifiers)
                            //                                && !method.isDefault()
                            && !method.isSynthetic()) {
                        pw.println(tabs + getNativeMethodCppDeclaration(method, javaClass));
                    }
                }
                pw.println(tabs + "void initContext(" + nativeClassName + "Context *ctx,bool isref);");
                pw.println(tabs + "void deleteContext();");
                tabs = tabs.substring(TAB_STRING.length());
                pw.println(tabs + "}; // end class " + nativeClassName);
            }
        }
        tabs = "";
        processTemplate(pw, map, HEADER_TEMPLATE_ENDH, tabs);
    }
    for (int segment_index = 0; segment_index < num_class_segments; segment_index++) {
        String header_segment_file = header_file_base + String.format(fmt, segment_index) + ".h";
        try (PrintWriter pw = new PrintWriter(new FileWriter(header_segment_file))) {
            tabs = "";
            //processTemplate(pw, map, HEADER_TEMPLATE_STARTH, tabs);
            pw.println("// Never include this file (" + header_segment_file + ") directly. include " + header
                    + " instead.");
            pw.println();
            Class lastClass = null;
            final int start_segment_index = segment_index * classes_per_file;
            final int end_segment_index = Math.min(segment_index * classes_per_file + classes_per_file,
                    classes.size());
            List<Class> classesSegList = classes.subList(start_segment_index, end_segment_index);
            pw.println();
            pw.println(tabs + "// start_segment_index = " + start_segment_index);
            pw.println(tabs + "// start_segment_index = " + end_segment_index);
            pw.println(tabs + "// segment_index = " + segment_index);
            pw.println(tabs + "// classesSegList=" + classesSegList);
            pw.println();
            for (int class_index = 0; class_index < classesSegList.size(); class_index++) {
                Class clss = classesSegList.get(class_index);
                pw.println();
                pw.println(tabs + "// class_index = " + class_index + " clss=" + clss);
                pw.println();
                String clssName = clss.getCanonicalName();
                tabs = openClassNamespace(clss, pw, tabs, lastClass);
                String clssOnlyName = getCppClassName(clss);
                map.put(CLASS_NAME, clssOnlyName);
                map.put("%BASE_CLASS_FULL_NAME%", classToCppBase(clss));
                map.put(OBJECT_CLASS_FULL_NAME, getCppRelativeName(Object.class, clss));
                tabs += TAB_STRING;
                processTemplate(pw, map, HEADER_CLASS_STARTH, tabs);
                tabs += TAB_STRING;

                Constructor constructors[] = clss.getDeclaredConstructors();
                if (!hasNoArgConstructor(constructors)) {
                    if (Modifier.isAbstract(clss.getModifiers()) || clss.isInterface()) {
                        pw.println(tabs + "protected:");
                        pw.println(tabs + clssOnlyName + "() {};");
                        pw.println(tabs + "public:");
                    } else {
                        if (constructors.length > 0) {
                            pw.println(tabs + "protected:");
                        }
                        pw.println(tabs + clssOnlyName + "();");
                        if (constructors.length > 0) {
                            pw.println(tabs + "public:");
                        }
                    }
                }
                for (Constructor c : constructors) {
                    if (c.getParameterTypes().length == 0 && Modifier.isProtected(c.getModifiers())) {
                        pw.println(tabs + "protected:");
                        pw.println(tabs + clssOnlyName + "();");
                        pw.println(tabs + "public:");
                    }
                    if (checkConstructor(c, clss, classes)) {
                        continue;
                    }

                    if (c.getParameterTypes().length == 1 && clss.isAssignableFrom(c.getParameterTypes()[0])) {
                        continue;
                    }
                    if (!Modifier.isPublic(c.getModifiers())) {
                        continue;
                    }
                    if (c.getParameterTypes().length == 1) {
                        if (c.getParameterTypes()[0].getName().equals(clss.getName())) {
                            //                                    if(verbose) System.out.println("skipping constructor.");
                            continue;
                        }
                    }

                    if (!checkParameters(c.getParameterTypes(), classes)) {
                        continue;
                    }
                    pw.println(
                            tabs + clssOnlyName + getCppParamDeclarations(c.getParameterTypes(), clss) + ";");
                    if (isConstructorToMakeEasy(c, clss)) {
                        pw.println(tabs + clssOnlyName
                                + getEasyCallCppParamDeclarations(c.getParameterTypes(), clss) + ";");
                    }
                }

                pw.println(tabs + "~" + clssOnlyName + "();");
                Field fa[] = clss.getDeclaredFields();
                for (int findex = 0; findex < fa.length; findex++) {
                    Field field = fa[findex];
                    if (addGetterMethod(field, clss, classes)) {
                        pw.println(tabs + getCppFieldGetterDeclaration(field, clss));
                    }
                    if (addSetterMethod(field, clss, classes)) {
                        pw.println(tabs + getCppFieldSetterDeclaration(field, clss));
                    }
                }
                Method methods[] = clss.getDeclaredMethods();
                for (int j = 0; j < methods.length; j++) {
                    Method method = methods[j];
                    if (!checkMethod(method, classes)) {
                        continue;
                    }
                    if ((method.getModifiers() & Modifier.PUBLIC) == Modifier.PUBLIC) {
                        pw.println(tabs + getCppDeclaration(method, clss));
                    }
                    if (isArrayStringMethod(method)) {
                        pw.println(tabs + getCppModifiers(method.getModifiers())
                                + getCppType(method.getReturnType(), clss) + " " + fixMethodName(method)
                                + "(int argc,const char **argv);");
                    }
                    if (isMethodToMakeEasy(method)) {
                        pw.println(tabs + getEasyCallCppDeclaration(method, clss));
                    }
                }
                tabs = tabs.substring(TAB_STRING.length());
                pw.println(tabs + "}; // end class " + clssOnlyName);
                tabs = tabs.substring(0, tabs.length() - 1);
                Class nextClass = (class_index < (classesSegList.size() - 1))
                        ? classesSegList.get(class_index + 1)
                        : null;
                tabs = closeClassNamespace(clss, pw, tabs, nextClass);
                pw.println();
                lastClass = clss;
            }
            //processTemplate(pw, map, HEADER_TEMPLATE_ENDH, tabs);
        }
    }
    for (int segment_index = 0; segment_index < num_class_segments; segment_index++) {
        String output_segment_file = output;
        if (output_segment_file.endsWith(".cpp")) {
            output_segment_file = output_segment_file.substring(0, output_segment_file.length() - 4);
        } else if (output_segment_file.endsWith(".cc")) {
            output_segment_file = output_segment_file.substring(0, output_segment_file.length() - 3);
        }
        output_segment_file += "" + String.format(fmt, segment_index) + ".cpp";
        try (PrintWriter pw = new PrintWriter(new FileWriter(output_segment_file))) {
            tabs = "";
            if (segment_index < 1) {
                processTemplate(pw, map, "cpp_template_start_first.cpp", tabs);
            } else {
                processTemplate(pw, map, CPP_TEMPLATE_STARTCPP, tabs);
            }
            final int start_segment_index = segment_index * classes_per_file;
            final int end_segment_index = Math.min(segment_index * classes_per_file + classes_per_file,
                    classes.size());
            List<Class> classesSegList = classes.subList(start_segment_index, end_segment_index);
            pw.println();
            pw.println(tabs + "// start_segment_index = " + start_segment_index);
            pw.println(tabs + "// start_segment_index = " + end_segment_index);
            pw.println(tabs + "// segment_index = " + segment_index);
            pw.println(tabs + "// classesSegList=" + classesSegList);
            pw.println();
            Class lastClass = null;
            for (int class_index = 0; class_index < classesSegList.size(); class_index++) {
                Class clss = classesSegList.get(class_index);
                pw.println();
                pw.println(tabs + "// class_index = " + class_index + " clss=" + clss);
                pw.println();
                String clssName = clss.getCanonicalName();
                tabs = openClassNamespace(clss, pw, tabs, lastClass);
                String clssOnlyName = getCppClassName(clss);
                map.put(CLASS_NAME, clssOnlyName);
                map.put("%BASE_CLASS_FULL_NAME%", classToCppBase(clss));

                map.put(FULL_CLASS_NAME, clssName);
                String fcjs = classToJNISignature(clss);
                fcjs = fcjs.substring(1, fcjs.length() - 1);
                map.put(FULL_CLASS_JNI_SIGNATURE, fcjs);
                if (verbose) {
                    System.out.println("fcjs = " + fcjs);
                }
                map.put(OBJECT_CLASS_FULL_NAME, getCppRelativeName(Object.class, clss));
                map.put("%INITIALIZE_CONTEXT%", "");
                map.put("%INITIALIZE_CONTEXT_REF%", "");
                processTemplate(pw, map, CPP_START_CLASSCPP, tabs);
                Constructor constructors[] = clss.getDeclaredConstructors();

                if (!hasNoArgConstructor(constructors)) {
                    if (!Modifier.isAbstract(clss.getModifiers()) && !clss.isInterface()) {
                        pw.println(tabs + clssOnlyName + "::" + clssOnlyName + "() : " + classToCppBase(clss)
                                + "((jobject)NULL,false) {");
                        map.put(JNI_SIGNATURE, "()V");
                        map.put(CONSTRUCTOR_ARGS, "");
                        processTemplate(pw, map, CPP_NEWCPP, tabs);
                        pw.println(tabs + "}");
                        pw.println();
                    }

                }
                for (Constructor c : constructors) {
                    if (checkConstructor(c, clss, classes)) {
                        continue;
                    }
                    Class[] paramClasses = c.getParameterTypes();
                    pw.println(tabs + clssOnlyName + "::" + clssOnlyName
                            + getCppParamDeclarations(paramClasses, clss) + " : " + classToCppBase(clss)
                            + "((jobject)NULL,false) {");
                    tabs = tabs + TAB_STRING;
                    map.put(JNI_SIGNATURE, "(" + getJNIParamSignature(paramClasses) + ")V");
                    map.put(CONSTRUCTOR_ARGS,
                            (paramClasses.length > 0 ? "," : "") + getCppParamNames(paramClasses));
                    processTemplate(pw, map, CPP_NEWCPP, tabs);
                    tabs = tabs.substring(0, tabs.length() - 1);
                    pw.println(tabs + "}");
                    pw.println();
                    if (isConstructorToMakeEasy(c, clss)) {
                        pw.println(tabs + clssOnlyName + "::" + clssOnlyName
                                + getEasyCallCppParamDeclarations(c.getParameterTypes(), clss) + " : "
                                + classToCppBase(clss) + "((jobject)NULL,false) {");
                        processTemplate(pw, map, "cpp_start_easy_constructor.cpp", tabs);
                        for (int paramIndex = 0; paramIndex < paramClasses.length; paramIndex++) {
                            Class paramClasse = paramClasses[paramIndex];
                            String parmName = getParamNameIn(paramClasse, paramIndex);
                            if (isString(paramClasse)) {
                                pw.println(tabs + "jstring " + parmName + " = env->NewStringUTF(easyArg_"
                                        + paramIndex + ");");
                            } else if (isPrimitiveArray(paramClasse)) {
                                String callString = getMethodCallString(paramClasse.getComponentType());
                                pw.println(tabs + getCppArrayType(paramClasse.getComponentType()) + " "
                                        + classToParamNameDecl(paramClasse, paramIndex) + "= env->New"
                                        + callString + "Array(easyArg_" + paramIndex + "_length);");
                                pw.println(tabs + "env->Set" + callString + "ArrayRegion("
                                        + classToParamNameDecl(paramClasse, paramIndex) + ",0,easyArg_"
                                        + paramIndex + "_length,easyArg_" + paramIndex + ");");
                            } else {
                                pw.println(tabs + getCppType(paramClasse, clss) + " "
                                        + classToParamNameDecl(paramClasse, paramIndex) + "= easyArg_"
                                        + paramIndex + ";");
                            }
                        }
                        processTemplate(pw, map, "cpp_new_easy_internals.cpp", tabs);
                        for (int paramIndex = 0; paramIndex < paramClasses.length; paramIndex++) {
                            Class paramClasse = paramClasses[paramIndex];
                            String parmName = getParamNameIn(paramClasse, paramIndex);
                            if (isString(paramClasse)) {
                                pw.println(tabs + "jobjectRefType ref_" + paramIndex
                                        + " = env->GetObjectRefType(" + parmName + ");");
                                pw.println(tabs + "if(ref_" + paramIndex + " == JNIGlobalRefType) {");
                                pw.println(tabs + TAB_STRING + "env->DeleteGlobalRef(" + parmName + ");");
                                pw.println(tabs + "}");
                            } else if (isPrimitiveArray(paramClasse)) {
                                String callString = getMethodCallString(paramClasse.getComponentType());
                                pw.println(tabs + "env->Get" + callString + "ArrayRegion("
                                        + classToParamNameDecl(paramClasse, paramIndex) + ",0,easyArg_"
                                        + paramIndex + "_length,easyArg_" + paramIndex + ");");
                                pw.println(tabs + "jobjectRefType ref_" + paramIndex
                                        + " = env->GetObjectRefType(" + parmName + ");");
                                pw.println(tabs + "if(ref_" + paramIndex + " == JNIGlobalRefType) {");
                                pw.println(tabs + TAB_STRING + "env->DeleteGlobalRef(" + parmName + ");");
                                pw.println(tabs + "}");
                            } else {

                            }
                        }
                        processTemplate(pw, map, "cpp_end_easy_constructor.cpp", tabs);
                        pw.println(tabs + "}");
                    }
                }

                pw.println();
                pw.println(tabs + "// Destructor for " + clssName);
                pw.println(tabs + clssOnlyName + "::~" + clssOnlyName + "() {");
                pw.println(tabs + "\t// Place-holder for later extensibility.");
                pw.println(tabs + "}");
                pw.println();
                Field fa[] = clss.getDeclaredFields();
                for (int findex = 0; findex < fa.length; findex++) {
                    Field field = fa[findex];
                    if (addGetterMethod(field, clss, classes)) {
                        pw.println();
                        pw.println(tabs + "// Field getter for " + field.getName());
                        pw.println(getCppFieldGetterDefinitionStart(tabs, clssOnlyName, field, clss));
                        map.put("%FIELD_NAME%", field.getName());
                        map.put(JNI_SIGNATURE, classToJNISignature(field.getType()));
                        Class returnClass = field.getType();
                        map.put(METHOD_ONFAIL, getOnFailString(returnClass, clss));
                        map.put(METHOD_ARGS, "");
                        map.put("%METHOD_RETURN%", isVoid(returnClass) ? "" : "return");
                        map.put("%METHOD_CALL_TYPE%", getMethodCallString(returnClass));
                        map.put("%METHOD_RETURN_TYPE%", getCppType(returnClass, clss));
                        map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass));
                        String retStore = isVoid(returnClass) ? ""
                                : "retVal= (" + getMethodReturnVarType(returnClass) + ") ";
                        map.put("%METHOD_RETURN_STORE%", retStore);
                        map.put("%METHOD_RETURN_GET%", getMethodReturnGet(tabs, returnClass, clss));

                        if (Modifier.isStatic(field.getModifiers())) {
                            processTemplate(pw, map, "cpp_static_getfield.cpp", tabs);
                        } else {
                            processTemplate(pw, map, "cpp_getfield.cpp", tabs);
                        }

                        pw.println(tabs + "}");
                    }
                    if (addSetterMethod(field, clss, classes)) {
                        pw.println();
                        pw.println(tabs + "// Field setter for " + field.getName());
                        pw.println(getCppFieldSetterDefinitionStart(tabs, clssOnlyName, field, clss));
                        map.put("%FIELD_NAME%", field.getName());
                        map.put(JNI_SIGNATURE, classToJNISignature(field.getType()));
                        Class returnClass = void.class;
                        map.put(METHOD_ONFAIL, getOnFailString(returnClass, clss));
                        Class[] paramClasses = new Class[] { field.getType() };
                        String methodArgs = getCppParamNames(paramClasses);
                        map.put(METHOD_ARGS, (paramClasses.length > 0 ? "," : "") + methodArgs);
                        map.put("%METHOD_RETURN%", isVoid(returnClass) ? "" : "return");
                        map.put("%METHOD_CALL_TYPE%", getMethodCallString(field.getType()));
                        map.put("%METHOD_RETURN_TYPE%", getCppType(returnClass, clss));
                        map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass));
                        String retStore = isVoid(returnClass) ? ""
                                : "retVal= (" + getMethodReturnVarType(returnClass) + ") ";
                        map.put("%METHOD_RETURN_STORE%", retStore);
                        map.put("%METHOD_RETURN_GET%", getMethodReturnGet(tabs, returnClass, clss));

                        if (Modifier.isStatic(field.getModifiers())) {
                            processTemplate(pw, map, "cpp_static_setfield.cpp", tabs);
                        } else {
                            processTemplate(pw, map, "cpp_setfield.cpp", tabs);
                        }

                        pw.println(tabs + "}");
                    }
                }
                Method methods[] = clss.getDeclaredMethods();
                for (int j = 0; j < methods.length; j++) {
                    Method method = methods[j];

                    if (checkMethod(method, classes)) {
                        pw.println();
                        pw.println(getCppMethodDefinitionStart(tabs, clssOnlyName, method, clss));
                        map.put(METHOD_NAME, method.getName());
                        if (fixMethodName(method).contains("equals2")) {
                            if (verbose) {
                                System.out.println("debug me");
                            }
                        }
                        map.put("%JAVA_METHOD_NAME%", method.getName());
                        Class[] paramClasses = method.getParameterTypes();
                        String methodArgs = getCppParamNames(paramClasses);
                        map.put(METHOD_ARGS, (paramClasses.length > 0 ? "," : "") + methodArgs);
                        Class returnClass = method.getReturnType();
                        map.put(JNI_SIGNATURE, "(" + getJNIParamSignature(paramClasses) + ")"
                                + classToJNISignature(returnClass));
                        map.put(METHOD_ONFAIL, getOnFailString(returnClass, clss));
                        map.put("%METHOD_RETURN%", isVoid(returnClass) ? "" : "return");
                        map.put("%METHOD_CALL_TYPE%", getMethodCallString(returnClass));
                        map.put("%METHOD_RETURN_TYPE%", getCppType(returnClass, clss));
                        map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass));
                        String retStore = isVoid(returnClass) ? ""
                                : "retVal= (" + getMethodReturnVarType(returnClass) + ") ";
                        map.put("%METHOD_RETURN_STORE%", retStore);
                        map.put("%METHOD_RETURN_GET%", getMethodReturnGet(tabs, returnClass, clss));
                        tabs += TAB_STRING;
                        if (!Modifier.isStatic(method.getModifiers())) {
                            processTemplate(pw, map, CPP_METHODCPP, tabs);
                        } else {
                            processTemplate(pw, map, CPP_STATIC_METHODCPP, tabs);
                        }
                        tabs = tabs.substring(0, tabs.length() - TAB_STRING.length());
                        pw.println(tabs + "}");
                        if (isArrayStringMethod(method)) {
                            map.put(METHOD_RETURN_STORE,
                                    isVoid(returnClass) ? "" : getCppType(returnClass, clss) + " returnVal=");
                            map.put(METHOD_RETURN_GET, isVoid(returnClass) ? "return ;" : "return returnVal;");
                            processTemplate(pw, map, CPP_EASY_STRING_ARRAY_METHODCPP, tabs);
                        } else if (isMethodToMakeEasy(method)) {
                            pw.println();
                            pw.println(tabs + "// Easy call alternative for " + method.getName());
                            pw.println(getEasyCallCppMethodDefinitionStart(tabs, clssOnlyName, method, clss));
                            tabs += TAB_STRING;
                            map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclareOut(returnClass, clss));
                            processTemplate(pw, map, "cpp_start_easy_method.cpp", tabs);
                            for (int paramIndex = 0; paramIndex < paramClasses.length; paramIndex++) {
                                Class paramClasse = paramClasses[paramIndex];
                                String parmName = getParamNameIn(paramClasse, paramIndex);
                                if (isString(paramClasse)) {
                                    pw.println(tabs + "jstring " + parmName + " = env->NewStringUTF(easyArg_"
                                            + paramIndex + ");");
                                } else if (isPrimitiveArray(paramClasse)) {
                                    String callString = getMethodCallString(paramClasse.getComponentType());
                                    pw.println(tabs + getCppArrayType(paramClasse.getComponentType()) + " "
                                            + classToParamNameDecl(paramClasse, paramIndex) + "= env->New"
                                            + callString + "Array(easyArg_" + paramIndex + "_length);");
                                    pw.println(tabs + "env->Set" + callString + "ArrayRegion("
                                            + classToParamNameDecl(paramClasse, paramIndex) + ",0,easyArg_"
                                            + paramIndex + "_length,easyArg_" + paramIndex + ");");
                                } else {
                                    pw.println(tabs + getCppType(paramClasse, clss) + " "
                                            + classToParamNameDecl(paramClasse, paramIndex) + "= easyArg_"
                                            + paramIndex + ";");
                                }
                            }
                            String methodArgsIn = getCppParamNamesIn(paramClasses);
                            String retStoreOut = isVoid(returnClass) ? ""
                                    : "retVal= (" + getMethodReturnOutVarType(returnClass, clss) + ") ";

                            pw.println(tabs + retStoreOut + fixMethodName(method) + "(" + methodArgsIn + ");");
                            for (int paramIndex = 0; paramIndex < paramClasses.length; paramIndex++) {
                                Class paramClasse = paramClasses[paramIndex];
                                String parmName = getParamNameIn(paramClasse, paramIndex);
                                if (isString(paramClasse)) {
                                    pw.println(tabs + "jobjectRefType ref_" + paramIndex
                                            + " = env->GetObjectRefType(" + parmName + ");");
                                    pw.println(tabs + "if(ref_" + paramIndex + " == JNIGlobalRefType) {");
                                    pw.println(tabs + TAB_STRING + "env->DeleteGlobalRef(" + parmName + ");");
                                    pw.println(tabs + "}");
                                } else if (isPrimitiveArray(paramClasse)) {
                                    String callString = getMethodCallString(paramClasse.getComponentType());
                                    pw.println(tabs + "env->Get" + callString + "ArrayRegion("
                                            + classToParamNameDecl(paramClasse, paramIndex) + ",0,easyArg_"
                                            + paramIndex + "_length,easyArg_" + paramIndex + ");");
                                    pw.println(tabs + "jobjectRefType ref_" + paramIndex
                                            + " = env->GetObjectRefType(" + parmName + ");");
                                    pw.println(tabs + "if(ref_" + paramIndex + " == JNIGlobalRefType) {");
                                    pw.println(tabs + TAB_STRING + "env->DeleteGlobalRef(" + parmName + ");");
                                    pw.println(tabs + "}");
                                } else {

                                }
                            }
                            processTemplate(pw, map, "cpp_end_easy_method.cpp", tabs);
                            if (!isVoid(returnClass)) {
                                pw.println(tabs + "return retVal;");
                            }
                            tabs = tabs.substring(TAB_STRING.length());
                            pw.println(tabs + "}");
                            pw.println();
                        }
                    }
                }
                processTemplate(pw, map, CPP_END_CLASSCPP, tabs);
                tabs = tabs.substring(0, tabs.length() - 1);
                Class nextClass = (class_index < (classesSegList.size() - 1))
                        ? classesSegList.get(class_index + 1)
                        : null;
                tabs = closeClassNamespace(clss, pw, tabs, nextClass);
                lastClass = clss;
            }

            if (segment_index < 1) {
                if (null != nativesClassMap) {
                    for (Entry<String, Class> e : nativesClassMap.entrySet()) {
                        final Class javaClass = e.getValue();
                        final String nativeClassName = e.getKey();
                        map.put(CLASS_NAME, nativeClassName);
                        map.put(FULL_CLASS_NAME, nativeClassName);
                        map.put(FULL_CLASS_JNI_SIGNATURE, nativeClassName);
                        map.put("%BASE_CLASS_FULL_NAME%",
                                "::" + namespace + "::" + getModifiedClassName(javaClass).replace(".", "::"));
                        map.put(OBJECT_CLASS_FULL_NAME, "::" + namespace + "::java::lang::Object");
                        map.put("%INITIALIZE_CONTEXT%", "context=NULL; initContext(NULL,false);");
                        map.put("%INITIALIZE_CONTEXT_REF%", "context=NULL; initContext(objref.context,true);");
                        tabs += TAB_STRING;

                        processTemplate(pw, map, CPP_START_CLASSCPP, tabs);
                        pw.println();
                        pw.println(tabs + nativeClassName + "::" + nativeClassName + "() : "
                                + getModifiedClassName(javaClass).replace(".", "::")
                                + "((jobject)NULL,false) {");
                        tabs += TAB_STRING;
                        pw.println(tabs + "context=NULL;");
                        pw.println(tabs + "initContext(NULL,false);");
                        map.put(JNI_SIGNATURE, "()V");
                        map.put(CONSTRUCTOR_ARGS, "");
                        processTemplate(pw, map, "cpp_new_native.cpp", tabs);
                        tabs = tabs.substring(TAB_STRING.length());
                        pw.println(tabs + "}");
                        pw.println();
                        pw.println(tabs + "// Destructor for " + nativeClassName);
                        pw.println(tabs + nativeClassName + "::~" + nativeClassName + "() {");
                        pw.println(tabs + TAB_STRING + "if(NULL != context) {");
                        pw.println(tabs + TAB_STRING + TAB_STRING + "deleteContext();");
                        pw.println(tabs + TAB_STRING + "}");
                        pw.println(tabs + TAB_STRING + "context=NULL;");
                        pw.println(tabs + "}");
                        pw.println();
                        //                            pw.println(tabs + "public:");
                        //                            pw.println(tabs + nativeClassName + "();");
                        //                            pw.println(tabs + "~" + nativeClassName + "();");
                        tabs = tabs.substring(TAB_STRING.length());
                        //                            Method methods[] = javaClass.getDeclaredMethods();
                        //                            for (int j = 0; j < methods.length; j++) {
                        //                                Method method = methods[j];
                        //                                int modifiers = method.getModifiers();
                        //                                if (!Modifier.isPublic(modifiers)) {
                        //                                    continue;
                        //                                }
                        //                                pw.println(tabs + getCppDeclaration(method, javaClass));
                        //                            }
                        //                            pw.println(tabs + "}; // end class " + nativeClassName);
                        processTemplate(pw, map, CPP_END_CLASSCPP, tabs);
                    }
                }
                processTemplate(pw, map, "cpp_template_end_first.cpp", tabs);
                tabs = "";
                if (null != nativesClassMap) {
                    pw.println("using namespace " + namespace + ";");
                    pw.println("#ifdef __cplusplus");
                    pw.println("extern \"C\" {");
                    pw.println("#endif");
                    int max_method_count = 0;
                    tabs = "";
                    for (Entry<String, Class> e : nativesClassMap.entrySet()) {
                        final Class javaClass = e.getValue();
                        final String nativeClassName = e.getKey();
                        map.put(CLASS_NAME, nativeClassName);
                        map.put(FULL_CLASS_NAME, nativeClassName);
                        map.put("%BASE_CLASS_FULL_NAME%",
                                "::" + namespace + "::" + getModifiedClassName(javaClass).replace(".", "::"));
                        map.put(OBJECT_CLASS_FULL_NAME, "::" + namespace + "::java::lang::Object");
                        map.put(FULL_CLASS_JNI_SIGNATURE, nativeClassName);
                        map.put(METHOD_ONFAIL, "return;");
                        Method methods[] = javaClass.getDeclaredMethods();
                        if (max_method_count < methods.length) {
                            max_method_count = methods.length;
                        }
                        for (int j = 0; j < methods.length; j++) {
                            Method method = methods[j];
                            int modifiers = method.getModifiers();
                            if (!Modifier.isPublic(modifiers)) {
                                continue;
                            }
                            if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers)
                                    && !Modifier.isStatic(modifiers)
                                    //                                        && !method.isDefault()
                                    && !method.isSynthetic()) {
                                Class[] paramClasses = method.getParameterTypes();
                                String methodArgs = getCppParamNames(paramClasses);
                                map.put(METHOD_ARGS, methodArgs);
                                map.put(METHOD_NAME, method.getName());
                                Class returnClass = method.getReturnType();
                                String retStore = isVoid(returnClass) ? ""
                                        : "retVal= (" + getMethodReturnVarType(returnClass) + ") ";
                                map.put(METHOD_ONFAIL, getOnFailString(returnClass, javaClass));
                                map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass));
                                map.put("%METHOD_RETURN_STORE%", retStore);
                                map.put("%METHOD_RETURN_GET%",
                                        getMethodReturnGet(tabs, returnClass, javaClass));
                                pw.println();
                                String paramDecls = getCppParamDeclarations(paramClasses, javaClass);
                                String argsToAdd = method.getParameterTypes().length > 0
                                        ? "," + paramDecls.substring(1, paramDecls.length() - 1)
                                        : "";
                                pw.println("JNIEXPORT " + getCppType(returnClass, javaClass) + " JNICALL Java_"
                                        + nativeClassName + "_" + method.getName()
                                        + "(JNIEnv *env, jobject jthis" + argsToAdd + ") {");
                                tabs = TAB_STRING;
                                processTemplate(pw, map, "cpp_native_wrap.cpp", tabs);
                                tabs = tabs.substring(TAB_STRING.length());
                                pw.println("}");
                                pw.println();
                            }
                        }
                        pw.println("JNIEXPORT void JNICALL Java_" + nativeClassName
                                + "_nativeDelete(JNIEnv *env, jobject jthis) {");
                        tabs += TAB_STRING;
                        map.put(METHOD_ONFAIL, getOnFailString(void.class, javaClass));
                        processTemplate(pw, map, "cpp_native_delete.cpp", tabs);
                        tabs = tabs.substring(TAB_STRING.length());
                        pw.println(tabs + "}");
                        pw.println();
                    }
                    pw.println("#ifdef __cplusplus");
                    pw.println("} // end extern \"C\"");
                    pw.println("#endif");
                    map.put("%MAX_METHOD_COUNT%", Integer.toString(max_method_count + 1));
                    processTemplate(pw, map, "cpp_start_register_native.cpp", tabs);
                    for (Entry<String, Class> e : nativesClassMap.entrySet()) {
                        final Class javaClass = e.getValue();
                        final String nativeClassName = e.getKey();
                        map.put(CLASS_NAME, nativeClassName);
                        map.put(FULL_CLASS_NAME, nativeClassName);
                        map.put("%BASE_CLASS_FULL_NAME%",
                                "::" + namespace + "::" + getModifiedClassName(javaClass).replace(".", "::"));
                        map.put(OBJECT_CLASS_FULL_NAME, "::" + namespace + "::java::lang::Object");
                        processTemplate(pw, map, "cpp_start_register_native_class.cpp", tabs);
                        tabs += TAB_STRING;
                        Method methods[] = javaClass.getDeclaredMethods();
                        int method_number = 0;
                        for (int j = 0; j < methods.length; j++) {
                            Method method = methods[j];
                            int modifiers = method.getModifiers();
                            if (!Modifier.isPublic(modifiers)) {
                                continue;
                            }
                            if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers)
                                    && !Modifier.isStatic(modifiers)
                                    //                                        && !method.isDefault()
                                    && !method.isSynthetic()) {
                                map.put("%METHOD_NUMBER%", Integer.toString(method_number));
                                map.put(METHOD_NAME, method.getName());

                                map.put(JNI_SIGNATURE, "(" + getJNIParamSignature(method.getParameterTypes())
                                        + ")" + classToJNISignature(method.getReturnType()));
                                processTemplate(pw, map, "cpp_register_native_item.cpp", tabs);
                                method_number++;
                            }
                        }
                        map.put("%METHOD_NUMBER%", Integer.toString(method_number));
                        map.put(METHOD_NAME, "nativeDelete");
                        map.put(JNI_SIGNATURE, "()V");
                        processTemplate(pw, map, "cpp_register_native_item.cpp", tabs);
                        map.put("%NUM_NATIVE_METHODS%", Integer.toString(method_number));
                        processTemplate(pw, map, "cpp_end_register_native_class.cpp", tabs);
                        tabs = tabs.substring(TAB_STRING.length());
                    }
                    processTemplate(pw, map, "cpp_end_register_native.cpp", tabs);
                } else {
                    pw.println("// No Native classes : registerNativMethods not needed.");
                    pw.println("static void registerNativeMethods(JNIEnv *env) {}");
                }

            } else {
                processTemplate(pw, map, CPP_TEMPLATE_ENDCPP, tabs);
            }
        }
        if (null != nativesClassMap) {
            tabs = "";
            for (Entry<String, Class> e : nativesClassMap.entrySet()) {
                String nativeClassName = e.getKey();
                File nativeClassHeaderFile = new File(
                        namespace.toLowerCase() + "_" + nativeClassName.toLowerCase() + ".h");
                map.put("%NATIVE_CLASS_HEADER%", nativeClassHeaderFile.getName());
                map.put(CLASS_NAME, nativeClassName);
                if (nativeClassHeaderFile.exists()) {
                    if (verbose) {
                        System.out.println("skipping " + nativeClassHeaderFile.getCanonicalPath()
                                + " since it already exists.");
                    }
                } else {
                    try (PrintWriter pw = new PrintWriter(new FileWriter(nativeClassHeaderFile))) {
                        processTemplate(pw, map, "header_native_imp.h", tabs);
                    }
                }
                File nativeClassCppFile = new File(
                        namespace.toLowerCase() + "_" + nativeClassName.toLowerCase() + ".cpp");
                if (nativeClassCppFile.exists()) {
                    if (verbose) {
                        System.out.println("skipping " + nativeClassCppFile.getCanonicalPath()
                                + " since it already exists.");
                    }
                } else {
                    try (PrintWriter pw = new PrintWriter(new FileWriter(nativeClassCppFile))) {
                        processTemplate(pw, map, "cpp_native_imp_start.cpp", tabs);
                        Class javaClass = e.getValue();
                        Method methods[] = javaClass.getDeclaredMethods();
                        int method_number = 0;
                        for (int j = 0; j < methods.length; j++) {
                            Method method = methods[j];
                            int modifiers = method.getModifiers();
                            if (!Modifier.isPublic(modifiers)) {
                                continue;
                            }
                            if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers)
                                    && !Modifier.isStatic(modifiers)
                                    //                                        && !method.isDefault()
                                    && !method.isSynthetic()) {
                                Class[] paramClasses = method.getParameterTypes();
                                //                                    String methodArgs = getCppParamNames(paramClasses);
                                String paramDecls = getCppParamDeclarations(paramClasses, javaClass);
                                String methodArgs = method.getParameterTypes().length > 0
                                        ? paramDecls.substring(1, paramDecls.length() - 1)
                                        : "";
                                map.put(METHOD_ARGS, methodArgs);
                                map.put(METHOD_NAME, method.getName());
                                Class returnClass = method.getReturnType();
                                String retStore = isVoid(returnClass) ? ""
                                        : "retVal= (" + getMethodReturnVarType(returnClass) + ") ";
                                map.put(METHOD_ONFAIL, getOnFailString(returnClass, javaClass));
                                map.put("%RETURN_TYPE%", getCppType(returnClass, javaClass));
                                map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass));
                                map.put("%METHOD_RETURN_STORE%", retStore);
                                map.put("%METHOD_RETURN_GET%",
                                        getMethodReturnGet(tabs, returnClass, javaClass));
                                processTemplate(pw, map, "cpp_native_imp_stub.cpp", tabs);
                            }
                        }
                        processTemplate(pw, map, "cpp_native_imp_end.cpp", tabs);
                    }
                }
            }
        }
    }

    main_completed = true;
}