Search in sources :

Example 16 with Constructor

use of java.lang.reflect.Constructor in project android_frameworks_base by ParanoidAndroid.

the class GenericInflater method createItem.

/**
     * Low-level function for instantiating by name. This attempts to
     * instantiate class of the given <var>name</var> found in this
     * inflater's ClassLoader.
     * 
     * <p>
     * There are two things that can happen in an error case: either the
     * exception describing the error will be thrown, or a null will be
     * returned. You must deal with both possibilities -- the former will happen
     * the first time createItem() is called for a class of a particular name,
     * the latter every time there-after for that class name.
     * 
     * @param name The full name of the class to be instantiated.
     * @param attrs The XML attributes supplied for this instance.
     * 
     * @return The newly instantied item, or null.
     */
public final T createItem(String name, String prefix, AttributeSet attrs) throws ClassNotFoundException, InflateException {
    Constructor constructor = (Constructor) sConstructorMap.get(name);
    try {
        if (null == constructor) {
            // Class not found in the cache, see if it's real,
            // and try to add it
            Class clazz = mContext.getClassLoader().loadClass(prefix != null ? (prefix + name) : name);
            constructor = clazz.getConstructor(mConstructorSignature);
            sConstructorMap.put(name, constructor);
        }
        Object[] args = mConstructorArgs;
        args[1] = attrs;
        return (T) constructor.newInstance(args);
    } catch (NoSuchMethodException e) {
        InflateException ie = new InflateException(attrs.getPositionDescription() + ": Error inflating class " + (prefix != null ? (prefix + name) : name));
        ie.initCause(e);
        throw ie;
    } catch (ClassNotFoundException e) {
        // If loadClass fails, we should propagate the exception.
        throw e;
    } catch (Exception e) {
        InflateException ie = new InflateException(attrs.getPositionDescription() + ": Error inflating class " + constructor.getClass().getName());
        ie.initCause(e);
        throw ie;
    }
}
Also used : Constructor(java.lang.reflect.Constructor) InflateException(android.view.InflateException) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) InflateException(android.view.InflateException) IOException(java.io.IOException)

Example 17 with Constructor

use of java.lang.reflect.Constructor in project jersey by jersey.

the class BasicTypesMessageProvider method readFrom.

@Override
public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
    final String entityString = readFromAsString(entityStream, mediaType);
    if (entityString.isEmpty()) {
        throw new NoContentException(LocalizationMessages.ERROR_READING_ENTITY_MISSING());
    }
    final PrimitiveTypes primitiveType = PrimitiveTypes.forType(type);
    if (primitiveType != null) {
        return primitiveType.convert(entityString);
    }
    final Constructor constructor = AccessController.doPrivileged(ReflectionHelper.getStringConstructorPA(type));
    if (constructor != null) {
        try {
            return type.cast(constructor.newInstance(entityString));
        } catch (Exception e) {
            throw new MessageBodyProcessingException(LocalizationMessages.ERROR_ENTITY_PROVIDER_BASICTYPES_CONSTRUCTOR(type));
        }
    }
    if (AtomicInteger.class.isAssignableFrom(type)) {
        return new AtomicInteger((Integer) PrimitiveTypes.INTEGER.convert(entityString));
    }
    if (AtomicLong.class.isAssignableFrom(type)) {
        return new AtomicLong((Long) PrimitiveTypes.LONG.convert(entityString));
    }
    throw new MessageBodyProcessingException(LocalizationMessages.ERROR_ENTITY_PROVIDER_BASICTYPES_UNKWNOWN(type));
}
Also used : AtomicLong(java.util.concurrent.atomic.AtomicLong) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Constructor(java.lang.reflect.Constructor) NoContentException(javax.ws.rs.core.NoContentException) NoContentException(javax.ws.rs.core.NoContentException) IOException(java.io.IOException) WebApplicationException(javax.ws.rs.WebApplicationException)

Example 18 with Constructor

use of java.lang.reflect.Constructor in project jersey by jersey.

the class PropertiesHelper method convertValue.

/**
     * Convert {@code Object} value to a value of the specified class type.
     *
     * @param value {@code Object} value to convert.
     * @param type conversion type.
     * @param <T> converted value type.
     * @return value converted to the specified class type.
     */
public static <T> T convertValue(Object value, Class<T> type) {
    if (!type.isInstance(value)) {
        // TODO: Move string value readers from server to common and utilize them here
        final Constructor constructor = AccessController.doPrivileged(ReflectionHelper.getStringConstructorPA(type));
        if (constructor != null) {
            try {
                return type.cast(constructor.newInstance(value));
            } catch (Exception e) {
            // calling the constructor wasn't successful - ignore and try valueOf()
            }
        }
        final Method valueOf = AccessController.doPrivileged(ReflectionHelper.getValueOfStringMethodPA(type));
        if (valueOf != null) {
            try {
                return type.cast(valueOf.invoke(null, value));
            } catch (Exception e) {
            // calling valueOf wasn't successful
            }
        }
        // at this point we don't know what to return -> return null
        if (LOGGER.isLoggable(Level.WARNING)) {
            LOGGER.warning(LocalizationMessages.PROPERTIES_HELPER_GET_VALUE_NO_TRANSFORM(String.valueOf(value), value.getClass().getName(), type.getName()));
        }
        return null;
    }
    return type.cast(value);
}
Also used : Constructor(java.lang.reflect.Constructor) Method(java.lang.reflect.Method)

Example 19 with Constructor

use of java.lang.reflect.Constructor in project jersey by jersey.

the class ParamInjectionResolver method resolve.

@Override
@SuppressWarnings("unchecked")
public Object resolve(Injectee injectee) {
    AnnotatedElement annotated = injectee.getParent();
    Annotation[] annotations;
    if (annotated.getClass().equals(Constructor.class)) {
        annotations = ((Constructor) annotated).getParameterAnnotations()[injectee.getPosition()];
    } else {
        annotations = annotated.getDeclaredAnnotations();
    }
    Class componentClass = injectee.getInjecteeClass();
    Type genericType = injectee.getRequiredType();
    final Type targetGenericType;
    if (injectee.isFactory()) {
        targetGenericType = ReflectionHelper.getTypeArgument(genericType, 0);
    } else {
        targetGenericType = genericType;
    }
    final Class<?> targetType = ReflectionHelper.erasure(targetGenericType);
    final Parameter parameter = Parameter.create(componentClass, componentClass, hasEncodedAnnotation(injectee), targetType, targetGenericType, annotations);
    final Supplier<?> paramValueSupplier = valueSupplierProvider.getValueSupplier(parameter);
    if (paramValueSupplier != null) {
        if (injectee.isFactory()) {
            return paramValueSupplier;
        } else {
            return paramValueSupplier.get();
        }
    }
    return null;
}
Also used : Type(java.lang.reflect.Type) Constructor(java.lang.reflect.Constructor) AnnotatedElement(java.lang.reflect.AnnotatedElement) Parameter(org.glassfish.jersey.server.model.Parameter) Annotation(java.lang.annotation.Annotation)

Example 20 with Constructor

use of java.lang.reflect.Constructor in project hackpad by dropbox.

the class VMBridge_jdk13 method newInterfaceProxy.

@Override
protected Object newInterfaceProxy(Object proxyHelper, final ContextFactory cf, final InterfaceAdapter adapter, final Object target, final Scriptable topScope) {
    Constructor<?> c = (Constructor<?>) proxyHelper;
    InvocationHandler handler = new InvocationHandler() {

        public Object invoke(Object proxy, Method method, Object[] args) {
            return adapter.invoke(cf, target, topScope, method, args);
        }
    };
    Object proxy;
    try {
        proxy = c.newInstance(new Object[] { handler });
    } catch (InvocationTargetException ex) {
        throw Context.throwAsScriptRuntimeEx(ex);
    } catch (IllegalAccessException ex) {
        // Shouls not happen
        throw Kit.initCause(new IllegalStateException(), ex);
    } catch (InstantiationException ex) {
        // Shouls not happen
        throw Kit.initCause(new IllegalStateException(), ex);
    }
    return proxy;
}
Also used : Constructor(java.lang.reflect.Constructor) AccessibleObject(java.lang.reflect.AccessibleObject) Method(java.lang.reflect.Method) InvocationHandler(java.lang.reflect.InvocationHandler) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Aggregations

Constructor (java.lang.reflect.Constructor)1311 InvocationTargetException (java.lang.reflect.InvocationTargetException)281 Method (java.lang.reflect.Method)252 IOException (java.io.IOException)128 Field (java.lang.reflect.Field)111 ArrayList (java.util.ArrayList)106 Test (org.junit.Test)92 DOMTestDocumentBuilderFactory (org.w3c.domts.DOMTestDocumentBuilderFactory)74 JUnitTestSuiteAdapter (org.w3c.domts.JUnitTestSuiteAdapter)73 List (java.util.List)61 JAXPDOMTestDocumentBuilderFactory (org.w3c.domts.JAXPDOMTestDocumentBuilderFactory)58 Map (java.util.Map)50 Type (java.lang.reflect.Type)39 Annotation (java.lang.annotation.Annotation)38 HashMap (java.util.HashMap)38 HashSet (java.util.HashSet)31 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)31 ParameterizedType (java.lang.reflect.ParameterizedType)30 File (java.io.File)20 URL (java.net.URL)20