Example usage for java.lang Class getClassLoader

List of usage examples for java.lang Class getClassLoader

Introduction

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

Prototype

@CallerSensitive
@ForceInline 
public ClassLoader getClassLoader() 

Source Link

Document

Returns the class loader for the class.

Usage

From source file:org.datacleaner.util.convert.StandardTypeConverter.java

@Override
public Object fromString(Class<?> type, String str) {
    if (ReflectionUtils.isString(type)) {
        return str;
    }/*  w  w  w .j a  v a 2  s . co m*/
    if (ReflectionUtils.isBoolean(type)) {
        return Boolean.valueOf(str);
    }
    if (ReflectionUtils.isCharacter(type)) {
        return Character.valueOf(str.charAt(0));
    }
    if (ReflectionUtils.isInteger(type)) {
        return Integer.valueOf(str);
    }
    if (ReflectionUtils.isLong(type)) {
        return Long.valueOf(str);
    }
    if (ReflectionUtils.isByte(type)) {
        return Byte.valueOf(str);
    }
    if (ReflectionUtils.isShort(type)) {
        return Short.valueOf(str);
    }
    if (ReflectionUtils.isDouble(type)) {
        return Double.valueOf(str);
    }
    if (ReflectionUtils.isFloat(type)) {
        return Float.valueOf(str);
    }
    if (ReflectionUtils.is(type, Class.class)) {
        try {
            return Class.forName(str);
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("Class not found: " + str, e);
        }
    }
    if (ReflectionUtils.is(type, EnumerationValue.class)) {
        return new EnumerationValue(str);
    }
    if (type.isEnum()) {
        try {
            Object[] enumConstants = type.getEnumConstants();

            // first look for enum constant matches
            Method nameMethod = Enum.class.getMethod("name");
            for (Object e : enumConstants) {
                String name = (String) nameMethod.invoke(e);
                if (name.equals(str)) {
                    return e;
                }
            }

            // check for aliased enums
            for (Object e : enumConstants) {
                String name = (String) nameMethod.invoke(e);
                Field field = type.getField(name);
                Alias alias = ReflectionUtils.getAnnotation(field, Alias.class);
                if (alias != null) {
                    String[] aliasValues = alias.value();
                    for (String aliasValue : aliasValues) {
                        if (aliasValue.equals(str)) {
                            return e;
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new IllegalStateException("Unexpected error occurred while examining enum", e);
        }
        throw new IllegalArgumentException("No such enum '" + str + "' in enum class: " + type.getName());
    }
    if (ReflectionUtils.isDate(type)) {
        return toDate(str);
    }
    if (ReflectionUtils.is(type, File.class)) {
        final FileResolver fileResolver = new FileResolver(_configuration);
        return fileResolver.toFile(str);
    }
    if (ReflectionUtils.is(type, Calendar.class)) {
        Date date = toDate(str);
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c;
    }
    if (ReflectionUtils.is(type, Pattern.class)) {
        try {
            return Pattern.compile(str);
        } catch (PatternSyntaxException e) {
            throw new IllegalArgumentException("Invalid regular expression syntax in '" + str + "'.", e);
        }
    }
    if (ReflectionUtils.is(type, java.sql.Date.class)) {
        Date date = toDate(str);
        return new java.sql.Date(date.getTime());
    }
    if (ReflectionUtils.isNumber(type)) {
        return ConvertToNumberTransformer.transformValue(str);
    }
    if (ReflectionUtils.is(type, Serializable.class)) {
        logger.warn("fromString(...): No built-in handling of type: {}, using deserialization", type.getName());
        byte[] bytes = (byte[]) _parentConverter.fromString(byte[].class, str);
        ChangeAwareObjectInputStream objectInputStream = null;
        try {
            objectInputStream = new ChangeAwareObjectInputStream(new ByteArrayInputStream(bytes));
            objectInputStream.addClassLoader(type.getClassLoader());
            Object obj = objectInputStream.readObject();
            return obj;
        } catch (Exception e) {
            throw new IllegalStateException("Could not deserialize to " + type + ".", e);
        } finally {
            FileHelper.safeClose(objectInputStream);
        }
    }

    throw new IllegalArgumentException("Could not convert to type: " + type.getName());
}

From source file:org.diorite.cfg.system.TemplateCreator.java

/**
 * Get template for given class.// w ww  .ja  v a  2s  .  c om
 *
 * @param clazz    class to get template.
 * @param create   if template should be created if it don't exisit yet.
 * @param cache    if template should be saved to memory if created.
 * @param recreate if template should be force re-created even if it exisit.
 * @param <T>      Type of template class
 *
 * @return template class or null.
 */
@SuppressWarnings("unchecked")
public static <T> Template<T> getTemplate(final Class<T> clazz, final boolean create, final boolean cache,
        final boolean recreate) {
    if (!recreate) {
        final Template<T> template = (Template<T>) templateMap.get(clazz);
        if (template != null) {
            return template;
        }
        if (!create) {
            return null;
        }
    }
    Supplier<T> def = null;
    {
        final CfgDelegateDefault annotation = clazz.getAnnotation(CfgDelegateDefault.class);
        if (annotation != null) {
            final String path = annotation.value();
            final Supplier<Object> basicDelegate = ConfigField.getBasicDelegate(path);
            if (basicDelegate != null) {
                def = (Supplier<T>) basicDelegate;
            } else if (path.equalsIgnoreCase("{new}")) {
                final ConstructorInvoker constructor = DioriteReflectionUtils.getConstructor(clazz);
                def = () -> (T) constructor.invoke();
            } else {
                final int sepIndex = path.indexOf("::");
                final Class<?> targetClass;
                final String methodName;
                if (sepIndex == -1) {
                    targetClass = clazz;
                    methodName = path;
                } else {
                    try {
                        Class<?> tmpClass = DioriteReflectionUtils
                                .tryGetCanonicalClass(path.substring(0, sepIndex));
                        if (tmpClass == null) {
                            tmpClass = DioriteReflectionUtils.tryGetCanonicalClass(
                                    clazz.getPackage().getName() + "." + path.substring(0, sepIndex));
                            if (tmpClass == null) {
                                tmpClass = DioriteReflectionUtils.getNestedClass(clazz,
                                        path.substring(0, sepIndex));
                            }
                        }
                        targetClass = tmpClass;
                    } catch (final Exception e) {
                        throw new RuntimeException("Can't find class for: " + path, e);
                    }
                    methodName = path.substring(sepIndex + 2);
                }
                if (targetClass == null) {
                    throw new RuntimeException("Can't find class for delegate: " + path);
                }
                final MethodInvoker methodInvoker = DioriteReflectionUtils.getMethod(targetClass, methodName,
                        false);
                if (methodInvoker == null) {
                    final ReflectGetter<Object> reflectGetter = DioriteReflectionUtils
                            .getReflectGetter(methodName, targetClass);
                    def = () -> (T) reflectGetter.get(null);
                } else {
                    def = () -> (T) methodInvoker.invoke(null);
                }
            }
        }
    }

    final boolean allFields;
    //        final boolean superFields;
    final boolean ignoreTransient;
    final String name;
    final String header;
    final String footer;
    final Collection<String> excludedFields = new HashSet<>(5);
    {
        final CfgClass cfgInfo = clazz.getAnnotation(CfgClass.class);
        if (cfgInfo != null) {
            allFields = cfgInfo.allFields();
            //                superFields = cfgInfo.superFields();
            ignoreTransient = cfgInfo.ignoreTransient();
            name = (cfgInfo.name() != null) ? cfgInfo.name() : clazz.getSimpleName();
            Collections.addAll(excludedFields, cfgInfo.excludeFields());
        } else {
            allFields = true;
            //                superFields = true;
            ignoreTransient = true;
            name = clazz.getSimpleName();
        }
    }
    {
        final String[] comments = readComments(clazz);
        header = comments[0];
        footer = comments[1];
    }

    final Set<ConfigField> fields = new TreeSet<>();

    {
        final Collection<Class<?>> classes = new ArrayList<>(5);
        {
            Class<?> fieldsSrc = clazz;
            do {
                classes.add(fieldsSrc);
                fieldsSrc = fieldsSrc.getSuperclass();
                if (fieldsSrc == null) {
                    break;
                }
                final CfgClass cfgInfo = fieldsSrc.getAnnotation(CfgClass.class);
                if ((cfgInfo != null) && !cfgInfo.superFields()) {
                    break;
                }
            } while (!fieldsSrc.equals(Object.class));
        }

        for (final Class<?> fieldsSrc : classes) {
            int i = 0;
            for (final Field field : fieldsSrc.getDeclaredFields()) {
                if ((field.isAnnotationPresent(CfgField.class)
                        || (!field.isAnnotationPresent(CfgExclude.class) && !field.isSynthetic()
                                && (!ignoreTransient || !Modifier.isTransient(field.getModifiers()))
                                && (allFields || field.isAnnotationPresent(CfgField.class))
                                && !excludedFields.contains(field.getName())))
                        && !Modifier.isStatic(field.getModifiers())) {
                    fields.add(new ConfigField(field, i++));
                }
            }
        }
    }
    final Template<T> template = new BaseTemplate<>(name, clazz, header, footer, fields, clazz.getClassLoader(),
            def);
    if (cache) {
        templateMap.put(clazz, template);
        TemplateCreator.fields.put(clazz, template.getFieldsNameMap());
    }
    return template;
}

From source file:org.gradle.initialization.ExceptionDecoratingClassGenerator.java

private <T> Class<? extends T> doGenerate(Class<T> type) {
    ClassWriter visitor = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    String typeName = StringUtils.substringBeforeLast(type.getName(), ".") + ".LocationAware"
            + type.getSimpleName();//from ww w. j  a va2 s  .  c o m
    Type generatedType = Type.getType("L" + typeName.replaceAll("\\.", "/") + ";");
    Type superclassType = Type.getType(type);

    visitor.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, generatedType.getInternalName(), null,
            superclassType.getInternalName(),
            new String[] { Type.getType(LocationAwareException.class).getInternalName() });

    Type helperType = Type.getType(ExceptionHelper.class);
    Type throwableType = Type.getType(Throwable.class);
    Type scriptSourceType = Type.getType(ScriptSource.class);
    Type integerType = Type.getType(Integer.class);

    // GENERATE private ExceptionHelper helper;
    visitor.visitField(Opcodes.ACC_PRIVATE, "helper", helperType.getDescriptor(), null, null);

    // GENERATE <init>(<type> target, ScriptSource source, Integer lineNumber)

    String methodDescriptor = Type.getMethodDescriptor(Type.VOID_TYPE,
            new Type[] { superclassType, scriptSourceType, integerType });
    MethodVisitor methodVisitor = visitor.visitMethod(Opcodes.ACC_PUBLIC, "<init>", methodDescriptor, null,
            new String[0]);
    methodVisitor.visitCode();

    boolean noArgsConstructor;
    try {
        type.getConstructor(type);
        noArgsConstructor = false;
    } catch (NoSuchMethodException e) {
        try {
            type.getConstructor();
            noArgsConstructor = true;
        } catch (NoSuchMethodException e1) {
            throw new IllegalArgumentException(String.format(
                    "Cannot create subtype for exception '%s'. It needs a zero-args or copy constructor.",
                    type.getName()));
        }
    }

    if (noArgsConstructor) {
        // GENERATE super()
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superclassType.getInternalName(), "<init>",
                Type.getMethodDescriptor(Type.VOID_TYPE, new Type[0]));
        // END super()
    } else {
        // GENERATE super(target)
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
        methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superclassType.getInternalName(), "<init>",
                Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { superclassType }));
        // END super(target)
    }

    // GENERATE helper = new ExceptionHelper(this, target, source, lineNumber)
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);

    methodVisitor.visitTypeInsn(Opcodes.NEW, helperType.getInternalName());
    methodVisitor.visitInsn(Opcodes.DUP);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
    methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, helperType.getInternalName(), "<init>",
            Type.getMethodDescriptor(Type.VOID_TYPE,
                    new Type[] { throwableType, throwableType, scriptSourceType, integerType }));

    methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, generatedType.getInternalName(), "helper",
            helperType.getDescriptor());

    // END helper = new ExceptionHelper(target)

    methodVisitor.visitInsn(Opcodes.RETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    // END <init>(<type> target, ScriptSource source, Integer lineNumber)

    for (Method method : ExceptionHelper.class.getDeclaredMethods()) {
        // GENERATE public <type> <method>() { return helper.<method>(); }
        methodDescriptor = Type.getMethodDescriptor(Type.getType(method.getReturnType()), new Type[0]);
        methodVisitor = visitor.visitMethod(Opcodes.ACC_PUBLIC, method.getName(), methodDescriptor, null,
                new String[0]);
        methodVisitor.visitCode();

        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitFieldInsn(Opcodes.GETFIELD, generatedType.getInternalName(), "helper",
                helperType.getDescriptor());
        methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, helperType.getInternalName(), method.getName(),
                methodDescriptor);

        methodVisitor.visitInsn(Opcodes.ARETURN);
        methodVisitor.visitMaxs(0, 0);
        methodVisitor.visitEnd();
        // END public <type> <method>() { return helper.<method>(); }
    }

    visitor.visitEnd();

    byte[] bytecode = visitor.toByteArray();
    return (Class<T>) ReflectionUtil.invoke(type.getClassLoader(), "defineClass",
            new Object[] { typeName, bytecode, 0, bytecode.length });
}

From source file:self.philbrown.droidQuery.$.java

/**
 * Remove a previously-attached event handler from the views in the current selection. 
 * This can remove events registered/*from   w  w  w. jav a2s  .co m*/
 * by {@link #bind(String, Object, Function)}, {@link #on(String, Function)}, {@link #click()}, 
 * etc.- or directly on the view.
 * @param eventType the name of the event to unbind
 */
public void unbind(String eventType) {
    String method = String.format(Locale.US, "setOn%sListener", capitalize(eventType));
    for (int i = 0; i < this.views.size(); i++) {
        View view = this.views.get(i);
        String listener = String.format(Locale.US, "%s.On%sListener", view.getClass().getName(),
                capitalize(eventType));
        try {
            //dynamically create instance of the listener interface

            Class<?> eventInterface = Class.forName(listener);
            Method setEventListener = view.getClass().getMethod(method, new Class<?>[] { eventInterface });
            EventHandlerCreator proxy = new EventHandlerCreator($.with(view), $.noop());
            Object eventHandler = Proxy.newProxyInstance(eventInterface.getClassLoader(),
                    new Class<?>[] { eventInterface }, proxy);
            setEventListener.invoke(view, eventInterface.cast(eventHandler));

        } catch (Throwable t) {
            Log.w("droidQuery", String.format(Locale.US, "Could not unbind from event %s.", eventType));
        }
    }

}

From source file:self.philbrown.droidQuery.$.java

/**
 * Binds the views in the current selection to the event. For example:
 * <pre>//from w ww  .j a  v a 2 s .  co m
 * $.with(myView).on("click", new Function() {
 *    public void invoke($ droidQuery, Object... args) {
 *       droidQuery.alert("View Clicked!");
 *    }
 * });
 * </pre>
 * @note that for events with multiple words, all words except the first are required to be 
 * capitalized. For example, to bind to a long-click event, both of the following are acceptable:
 * <pre>
 * $.with(myView).on("longClick", new Function() {
 *    public void invoke($droidQuery, Object... args) {
 *       droidQuery.alert("View LongClicked!");
 *    }
 * });
 * 
 * $.with(myView).on("LongClick", new Function() {
 *    public void invoke($ droidQuery, Object... args) {
 *       droidQuery.alert("View LongClicked!");
 *    }
 * });
 * </pre>
 * However, this will fail:
 * <pre>
 * $.with(myView).on("longclick", new Function() {
 *    public void invoke($ droidQuery, Object... args) {
 *       droidQuery.alert("View LongClicked!");
 *    }
 * });
 * </pre>
 * @param event should be the verb in OnVerbListener
 * @param handler receives one argument: a droidQuery with the affected view selected
 * @return the current instance of {@code droidQuery}
 * @see #bind(String, Object, Function)
 * @see #one(String, Function)
 * @see #unbind(String)
 */
public $ on(String event, Function handler) {
    String method = String.format(Locale.US, "setOn%sListener", capitalize(event));
    String listener = String.format(Locale.US, "On%sListener", capitalize(event));
    for (int i = 0; i < this.views.size(); i++) {
        View view = this.views.get(i);
        Class<?>[] classes = view.getClass().getClasses();

        try {

            Class<?> eventInterface = null;

            for (Class<?> clazz : classes) {
                if (clazz.getSimpleName().equalsIgnoreCase(listener)) {
                    eventInterface = clazz;
                    break;
                }
            }

            Method setEventListener = view.getClass().getMethod(method, new Class<?>[] { eventInterface });
            EventHandlerCreator proxy = new EventHandlerCreator($.with(view), handler);
            Object eventHandler = Proxy.newProxyInstance(eventInterface.getClassLoader(),
                    new Class<?>[] { eventInterface }, proxy);
            setEventListener.invoke(view, eventInterface.cast(eventHandler));
        } catch (Throwable t) {
            Log.w("droidQuery", String.format(Locale.US, "Could not bind to event %s.", event));
        }
    }

    return this;
}

From source file:self.philbrown.droidQuery.$.java

/**
 * Binds the views in the current selection to the event. For example:
 * <pre>/*from   w  w w.  j  av  a  2  s.c  o m*/
 * $.with(myView).bind("click", "Hello World!", new Function() {
 *    public void invoke($ droidQuery, Object... args) {
 *       Object data = args[0];
 *       droidQuery.alert((String) data);
 *    }
 * });
 * </pre>
 * @note that for events with multiple words, all words except the first are required to be 
 * capitalized. For example, to bind to a long-click event, both of the following are acceptable:
 * <pre>
 * $.with(myView).bind("longClick", "Hello World!", new Function() {
 *    public void invoke($ droidQuery, Object... args) {
 *       Object data = args[0];
 *       droidQuery.alert((String) data);
 *    }
 * });
 * 
 * $.with(myView).bind("LongClick", "Hello World!", new Function() {
 *    public void invoke($ droidQuery, Object... args) {
 *       Object data = args[0];
 *       droidQuery.alert((String) data);
 *    }
 * });
 * </pre>
 * However, this will fail:
 * <pre>
 * $.with(myView).bind("longclick", "Hello World!", new Function() {
 *    public void invoke($ droidQuery, Object... args) {
 *       Object data = args[0];
 *       droidQuery.alert((String) data);
 *    }
 * });
 * </pre>
 * @param eventType should be the verb in OnVerbListener
 * @param data an Object passed to {@code handler} when the event is triggered.
 * @param handler receives two arguments: a droidQuery with the affected view selected, and the {@code data} parameter
 * @return the current instance of {@code droidQuery}
 * @see #on(String, Function)
 * @see #one(String, Function)
 * @see #unbind(String)
 */
public $ bind(String eventType, Object data, Function handler) {
    String method = String.format(Locale.US, "setOn%sListener", capitalize(eventType));
    String listener = String.format(Locale.US, "On%sListener", capitalize(eventType));
    for (int i = 0; i < this.views.size(); i++) {
        View view = this.views.get(i);
        Class<?>[] classes = view.getClass().getClasses();
        try {
            //dynamically create instance of the listener interface

            Class<?> eventInterface = null;

            for (Class<?> clazz : classes) {
                if (clazz.getSimpleName().equalsIgnoreCase(listener)) {
                    eventInterface = clazz;
                    break;
                }
            }
            Method setEventListener = view.getClass().getMethod(method, new Class<?>[] { eventInterface });
            EventHandlerCreator proxy = new EventHandlerCreator($.with(view), handler, data);
            Object eventHandler = Proxy.newProxyInstance(eventInterface.getClassLoader(),
                    new Class<?>[] { eventInterface }, proxy);
            setEventListener.invoke(view, eventInterface.cast(eventHandler));

        } catch (Throwable t) {
            Log.w("droidQuery",
                    String.format(Locale.US, "Could not bind to event %s.\n%s", eventType, t.getMessage()));
        }
    }

    return this;
}

From source file:self.philbrown.droidQuery.$.java

/**
 * Registers change listeners for TextViews, EditTexts, and CompoundButtons. For all other
 * view types, this will trigger a function when the view's layout has been changed.
 * @param function the Function to call when the change event occurs. This will receive a
 * droidQuery instance for the changed view
 * @return this// w ww  .j a  v  a 2s  . com
 */
public $ change(final Function function) {
    for (int i = 0; i < this.views.size(); i++) {
        View view = this.views.get(i);
        final int index = i;
        if (view instanceof TextView) {
            ((TextView) view).addTextChangedListener(new TextWatcher() {

                @Override
                public void afterTextChanged(Editable arg0) {
                    function.invoke($.with($.this.views.get(index)));
                }

                @Override
                public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

            });
        } else if (view instanceof EditText) {//this is overkill, but what the hey
            ((EditText) view).addTextChangedListener(new TextWatcher() {

                @Override
                public void afterTextChanged(Editable arg0) {
                    function.invoke($.with($.this.views.get(index)));
                }

                @Override
                public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

            });
        } else if (view instanceof CompoundButton) {
            ((CompoundButton) view).setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    function.invoke($.with($.this.views.get(index)));
                }

            });
        } else if (android.os.Build.VERSION.SDK_INT >= 11) {
            //default to size for API 11+
            try {
                Class<?> eventInterface = Class.forName("android.view.View.OnLayoutChangeListener");
                Method addOnLayoutChangeListener = view.getClass().getMethod("addOnLayoutChangeListener",
                        new Class<?>[] { eventInterface });
                InvocationHandler proxy = new InvocationHandler() {

                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        function.invoke($.with($.this.views.get(index)));
                        return null;
                    }

                };
                Object eventHandler = Proxy.newProxyInstance(eventInterface.getClassLoader(),
                        new Class<?>[] { eventInterface }, proxy);
                addOnLayoutChangeListener.invoke(view, eventInterface.cast(eventHandler));
            } catch (Throwable t) {
                //unknown error
            }
        }
    }

    return this;
}

From source file:com.nginious.http.serialize.JsonSerializerCreator.java

/**
 * Creates a JSON serializer for the specified bean class unless a serializer has already been
 * created. Created serializers are cached and returned on subsequent calls to this method.
 * //from  w ww  .j  a  v  a  2s. co  m
 * @param factory serializer factory
 * @param <T> class type for bean
 * @param beanClazz bean class for which a serializer should be created
 * @return the created serializer
 * @throws SerializerFactoryException if unable to create serializer or class is not a bean
 */
@SuppressWarnings("unchecked")
<T> JsonSerializer<T> create(SerializerFactoryImpl factory, Class<T> beanClazz)
        throws SerializerFactoryException {
    JsonSerializer<T> serializer = (JsonSerializer<T>) serializers.get(beanClazz);

    if (serializer != null) {
        return serializer;
    }

    try {
        synchronized (this) {
            serializer = (JsonSerializer<T>) serializers.get(beanClazz);

            if (serializer != null) {
                return serializer;
            }

            checkSerializability(beanClazz, "json");
            String intBeanClazzName = Serialization.createInternalClassName(beanClazz);
            Method[] methods = beanClazz.getMethods();

            String intSerializerClazzName = new StringBuffer(intBeanClazzName).append("JsonSerializer")
                    .toString();

            // Create class
            ClassWriter writer = new ClassWriter(0);
            String signature = Serialization.createClassSignature("com/nginious/http/serialize/JsonSerializer",
                    intBeanClazzName);
            writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, intSerializerClazzName, signature,
                    "com/nginious/http/serialize/JsonSerializer", null);

            // Create constructor
            Serialization.createConstructor(writer, "com/nginious/http/serialize/JsonSerializer");

            // Create serialize method
            MethodVisitor visitor = createSerializeMethod(writer, intBeanClazzName);

            for (Method method : methods) {
                Serializable info = method.getAnnotation(Serializable.class);
                boolean canSerialize = info == null
                        || (info != null && info.serialize() && info.types().indexOf("json") > -1);

                if (canSerialize && method.getName().startsWith("get") && !method.getName().equals("getClass")
                        && method.getReturnType() != null && method.getParameterTypes().length == 0) {
                    Class<?> returnType = method.getReturnType();
                    String propertyName = getPropertyName(method);

                    if (returnType.isPrimitive()) {
                        if (returnType.equals(boolean.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeBoolean",
                                    "Z", "Z", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(double.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeDouble",
                                    "D", "D", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(float.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeFloat",
                                    "F", "F", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(int.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeInt",
                                    "I", "I", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(long.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeLong",
                                    "J", "J", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(short.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeShort",
                                    "S", "S", intBeanClazzName, method.getName(), propertyName);
                        }
                    } else if (Collection.class.isAssignableFrom(returnType)) {
                        Class<?> collectionType = canSerializeGenericCollectionType(method, "json");

                        if (collectionType != null) {
                            createBeanCollectionSerializationCode(visitor, intBeanClazzName, method.getName(),
                                    propertyName, returnType, collectionType);
                        } else {
                            createObjectCollectionSerializationCode(visitor, returnType, intBeanClazzName,
                                    method.getName(), propertyName);
                        }
                    } else if (returnType.equals(Calendar.class)) {
                        createPropertySerializationCode(visitor, intSerializerClazzName, "serializeCalendar",
                                "Ljava/util/Calendar;", "Ljava/util/Calendar;", intBeanClazzName,
                                method.getName(), propertyName);
                    } else if (returnType.equals(Date.class)) {
                        createPropertySerializationCode(visitor, intSerializerClazzName, "serializeDate",
                                "Ljava/util/Date;", "Ljava/util/Date;", intBeanClazzName, method.getName(),
                                propertyName);
                    } else if (returnType.equals(String.class)) {
                        createPropertySerializationCode(visitor, intSerializerClazzName, "serializeString",
                                "Ljava/lang/String;", "Ljava/lang/String;", intBeanClazzName, method.getName(),
                                propertyName);
                    } else {
                        info = returnType.getAnnotation(Serializable.class);
                        canSerialize = info != null && info.serialize() && info.types().indexOf("json") > -1;

                        if (canSerialize) {
                            createBeanSerializationCode(visitor, method.getName(), propertyName, returnType,
                                    intBeanClazzName);
                        } else {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeObject",
                                    "Ljava/lang/Object;", "L" + returnType.getName().replace('.', '/') + ";",
                                    intBeanClazzName, method.getName(), propertyName);
                        }
                    }
                }
            }

            visitor.visitInsn(Opcodes.RETURN);
            visitor.visitMaxs(8, 7);
            visitor.visitEnd();

            writer.visitEnd();
            byte[] clazzBytes = writer.toByteArray();
            ClassLoader controllerLoader = null;

            if (classLoader.hasLoaded(beanClazz)) {
                controllerLoader = beanClazz.getClassLoader();
            } else {
                controllerLoader = this.classLoader;
            }

            Class<?> clazz = Serialization.loadClass(controllerLoader, intSerializerClazzName.replace('/', '.'),
                    clazzBytes);
            serializer = (JsonSerializer<T>) clazz.newInstance();
            String propertyName = Serialization.createPropertyNameFromClass(beanClazz);
            serializer.setName(propertyName);
            serializer.setType(beanClazz);
            serializer.setSerializerFactory(factory);
            serializers.put(beanClazz, serializer);
            return serializer;
        }
    } catch (IllegalAccessException e) {
        throw new SerializerFactoryException("Can't create JSON serializer for " + beanClazz.getName(), e);
    } catch (InstantiationException e) {
        throw new SerializerFactoryException("Can't create JSON serializer for " + beanClazz.getName(), e);
    }
}

From source file:com.nginious.http.serialize.JsonDeserializerCreator.java

/**
 * Creates a JSON deserializer for the specified bean class unless a deserializer has already
 * been created. Created deserializers are cached and returned on subsequent calls to this method.
 * /*from w w w . j a  v  a  2s  .co m*/
 * @param <T> class type for bean
 * @param beanClazz bean class for which a deserializer should be created
 * @return the created deserializer
 * @throws SerializerFactoryException if unable to create deserializer or class is not a bean
 */
@SuppressWarnings("unchecked")
protected <T> JsonDeserializer<T> create(Class<T> beanClazz) throws SerializerFactoryException {
    JsonDeserializer<T> deserializer = (JsonDeserializer<T>) deserializers.get(beanClazz);

    if (deserializer != null) {
        return deserializer;
    }

    try {
        synchronized (this) {
            deserializer = (JsonDeserializer<T>) deserializers.get(beanClazz);

            if (deserializer != null) {
                return deserializer;
            }

            checkDeserializability(beanClazz, "json");
            String intBeanClazzName = Serialization.createInternalClassName(beanClazz);
            Method[] methods = beanClazz.getMethods();

            String intDeserializerClazzName = new StringBuffer(intBeanClazzName).append("JsonDeserializer")
                    .toString();

            // Create class
            ClassWriter writer = new ClassWriter(0);
            String signature = Serialization
                    .createClassSignature("com/nginious/http/serialize/JsonDeserializer", intBeanClazzName);
            writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, intDeserializerClazzName, signature,
                    "com/nginious/http/serialize/JsonDeserializer", null);

            // Create constructor
            Serialization.createConstructor(writer, "com/nginious/http/serialize/JsonDeserializer");

            // Create deserialize method
            MethodVisitor visitor = createDeserializeMethod(writer, intBeanClazzName);

            for (Method method : methods) {
                Serializable info = method.getAnnotation(Serializable.class);
                boolean canDeserialize = info == null
                        || (info != null && info.deserialize() && info.types().indexOf("json") > -1);

                if (canDeserialize && method.getName().startsWith("set")
                        && method.getReturnType().equals(void.class)
                        && method.getParameterTypes().length == 1) {
                    Class<?>[] parameterTypes = method.getParameterTypes();
                    Class<?> parameterType = parameterTypes[0];

                    if (parameterType.isArray()) {
                        Class<?> arrayType = parameterType.getComponentType();

                        if (arrayType.equals(boolean.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeBooleanArray", "[Z", "[Z", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(double.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeDoubleArray", "[D", "[D", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(float.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeFloatArray", "[F", "[F", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(int.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeIntArray", "[I", "[I", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(long.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeLongArray", "[J", "[J", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(short.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeShortArray", "[S", "[S", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(String.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeStringArray", "[Ljava/lang/String;", "[Ljava/lang/String;",
                                    intBeanClazzName, method.getName());
                        }
                    } else if (parameterType.isPrimitive()) {
                        if (parameterType.equals(boolean.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeBoolean", "Z", "Z", intBeanClazzName, method.getName());
                        } else if (parameterType.equals(double.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeDouble", "D", "D", intBeanClazzName, method.getName());
                        } else if (parameterType.equals(float.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeFloat", "F", "F", intBeanClazzName, method.getName());
                        } else if (parameterType.equals(int.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeInt", "I", "I", intBeanClazzName, method.getName());
                        } else if (parameterType.equals(long.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeLong", "J", "J", intBeanClazzName, method.getName());
                        } else if (parameterType.equals(short.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeShort", "S", "S", intBeanClazzName, method.getName());
                        }
                    } else if (parameterType.equals(Calendar.class)) {
                        createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                "deserializeCalendar", "Ljava/util/Calendar;", "Ljava/util/Calendar;",
                                intBeanClazzName, method.getName());
                    } else if (parameterType.equals(Date.class)) {
                        createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeDate",
                                "Ljava/util/Date;", "Ljava/util/Date;", intBeanClazzName, method.getName());
                    } else if (parameterType.equals(String.class)) {
                        createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                "deserializeString", "Ljava/lang/String;", "Ljava/lang/String;",
                                intBeanClazzName, method.getName());
                    }
                }
            }

            visitor.visitVarInsn(Opcodes.ALOAD, 3);
            visitor.visitInsn(Opcodes.ARETURN);
            visitor.visitMaxs(5, 4);
            visitor.visitEnd();

            writer.visitEnd();
            byte[] clazzBytes = writer.toByteArray();
            ClassLoader controllerLoader = null;

            if (classLoader.hasLoaded(beanClazz)) {
                controllerLoader = beanClazz.getClassLoader();
            } else {
                controllerLoader = this.classLoader;
            }

            Class<?> clazz = Serialization.loadClass(controllerLoader,
                    intDeserializerClazzName.replace('/', '.'), clazzBytes);
            deserializer = (JsonDeserializer<T>) clazz.newInstance();
            deserializers.put(beanClazz, deserializer);
            return deserializer;
        }
    } catch (IllegalAccessException e) {
        throw new SerializerFactoryException(e);
    } catch (InstantiationException e) {
        throw new SerializerFactoryException(e);
    }
}