alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

What this is

This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Other links

The source code

/*
 *                 Sun Public License Notice
 * 
 * The contents of this file are subject to the Sun Public License
 * Version 1.0 (the "License"). You may not use this file except in
 * compliance with the License. A copy of the License is available at
 * http://www.sun.com/
 * 
 * The Original Code is NetBeans. The Initial Developer of the Original
 * Code is Sun Microsystems, Inc. Portions Copyright 1997-2000 Sun
 * Microsystems, Inc. All Rights Reserved.
 */

package org.netbeans.modules.form;

import java.util.*;
import java.lang.reflect.*;
import org.netbeans.modules.form.codestructure.*;

/**
 * @author Tomas Pavek
 */

public class ConstructorsDescriptor implements CreationDescriptor {

    private Class describedClass;
    private ConstructorCreator[] constructors;
    private Object[] defaultConstrParams;
    private Constructor defaultConstructor;

    private static final Class[] emptyTypes = { };
    private static final String[] emptyNames = { };
    private static final Object[] emptyParams = { };


    public ConstructorsDescriptor(Class descClass,
                                  Class[][] constrParamTypes,
                                  String[][] constrPropNames,
                                  Object[] defParams)
        throws NoSuchMethodException // if some constructor is not found
    {
        describedClass = descClass;

        if (constrParamTypes != null && constrParamTypes.length > 0) {
            constructors = new ConstructorCreator[constrParamTypes.length];
            for (int i=0; i < constrParamTypes.length; i++)
                constructors[i] = new ConstructorCreator(describedClass,
                                                         constrParamTypes[i],
                                                         constrPropNames[i]);
        }

        defaultConstrParams = defParams == null ? emptyParams : defParams;
        if (defaultConstrParams.length > 0)
            findDefaultConstructor();
    }

    public ConstructorsDescriptor(Class descClass) {
//        throws NoSuchMethodException // if public empty constructor doesn't exist
        describedClass = descClass;

        try {
            ConstructorCreator creator = new ConstructorCreator(describedClass,
                                                                emptyTypes,
                                                                emptyNames);
            constructors = new ConstructorCreator[] { creator };
        }
        catch (NoSuchMethodException ex) { // ignore
            if (Boolean.getBoolean("netbeans.debug.exceptions")) { // NOI18N
                System.out.println("[WARNING] No default constructor for "+descClass.getName()); // NOI18N
                ex.printStackTrace();
            }
        }

        defaultConstrParams = emptyParams;
    }

    // ---------

    public Class getDescribedClass() {
        return describedClass;
    }

    public Creator[] getCreators() {
        return constructors;
    }

    public Creator findBestCreator(FormProperty[] properties, int style) {
        if (constructors == null)
            return null;

        int[] evals = CreationFactory.evaluateCreators(
                        constructors, properties, (style & CHANGED_ONLY) != 0);
        int best = CreationFactory.getBestCreator(
                     constructors, properties, evals, (style & PLACE_ALL) != 0);
        return constructors[best];
    }

    public Object createDefaultInstance() throws InstantiationException,
                                                 IllegalAccessException,
                                                 IllegalArgumentException,
                                                 InvocationTargetException
    {
        if (defaultConstrParams.length == 0)
            return describedClass.newInstance();

        return defaultConstructor.newInstance(defaultConstrParams);
    }

    // ----------

    // finds first constructor that matches defaultConstrParams
    private void findDefaultConstructor() throws NoSuchMethodException {
        Constructor[] constructors = describedClass.getConstructors();
        for (int i=0; i < constructors.length; i++) {
            Class[] paramTypes = constructors[i].getParameterTypes();
            if (paramTypes.length == defaultConstrParams.length) {
                int ii;
                for (ii=0; ii < paramTypes.length; ii++) {
                    Class cls = paramTypes[ii];
                    Object param = defaultConstrParams[ii];

                    if (cls.isPrimitive()) {
                        if (param == null
                            || (param instanceof Integer && cls != Integer.TYPE)
                            || (param instanceof Boolean && cls != Boolean.TYPE)
                            || (param instanceof Double && cls != Double.TYPE)
                            || (param instanceof Long && cls != Long.TYPE)
                            || (param instanceof Float && cls != Float.TYPE)
                            || (param instanceof Short && cls != Short.TYPE)
                            || (param instanceof Byte && cls != Byte.TYPE)
                            || (param instanceof Character && cls != Character.TYPE))
                        break;
                    }
                    else if (param != null && !cls.isInstance(param))
                        break;
                }
                if (ii == paramTypes.length) {
                    defaultConstructor = constructors[i];
                    return;
                }
            }
        }
        throw new NoSuchMethodException();
    }

    // ----------

    static class ConstructorCreator implements Creator {
        private Class theClass;
        private Constructor constructor;
//        private Class[] constructorParamTypes;
        private String[] constructorPropNames;

        ConstructorCreator(Class cls, Class[] paramTypes, String[] propNames)
            throws NoSuchMethodException
        {
            if (paramTypes == null)
                paramTypes = emptyTypes;
            if (propNames == null)
                propNames = emptyNames;
            if (paramTypes.length != propNames.length)
                throw new IllegalArgumentException();

            constructor = cls.getConstructor(paramTypes);
            theClass = cls;
//            constructorParamTypes = paramTypes;
            constructorPropNames = propNames;
        }

        public final int getParameterCount() {
            return constructorPropNames.length; //constructorParamTypes.length;
        }

        public final Class[] getParameterTypes() {
            return constructor.getParameterTypes(); //constructorParamTypes;
        }

        public final Class[] getExceptionTypes() {
            return constructor.getExceptionTypes();
        }

        public final String[] getPropertyNames() {
            return constructorPropNames;
        }

        public Object createInstance(FormProperty[] props)
            throws InstantiationException, IllegalAccessException,
                   IllegalArgumentException, InvocationTargetException
        {
//            Constructor constr = null;
            Object[] paramValues = new Object[constructorPropNames.length];

            try {
//                paramValues = new Object[constructorPropNames.length];
//                Class[] paramTypes = new Class[constructorPropNames.length];

                for (int i=0; i < constructorPropNames.length; i++) {
                    FormProperty prop = CreationFactory.findProperty(
                                            constructorPropNames[i], props);
                    if (prop == null)
                        return null; // should not happen

                    paramValues[i] = prop.getRealValue();
//                    paramTypes[i] = prop.getValueType();
                }

//                constr = theClass.getConstructor(paramTypes);
            }
            catch (Exception ex) {
                if (Boolean.getBoolean("netbeans.debug.exceptions")) // NOI18N
                    ex.printStackTrace();
                throw new InstantiationException(ex.getMessage());
            }

            return constructor.newInstance(paramValues);
        }

        public String getJavaCreationCode(FormProperty[] props) {
            StringBuffer buf = new StringBuffer();
            buf.append("new "); // NOI18N
            buf.append(theClass.getName().replace('$', '.'));
            buf.append("("); // NOI18N

            for (int i=0; i < constructorPropNames.length; i++) {
                FormProperty prop = CreationFactory.findProperty(
                                        constructorPropNames[i], props);
                if (prop == null)
                    return null; // should not happen

                buf.append(prop.getJavaInitializationString());
                if (i+1 < constructorPropNames.length)
                    buf.append(", "); // NOI18N
            }

            buf.append(")"); // NOI18N
            return buf.toString();
        }

        public CodeExpressionOrigin getCodeOrigin(CodeExpression[] params) {
            return CodeStructure.createOrigin(constructor, params);
        }
    }
}
... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.