Example usage for java.lang.reflect Method getDeclaringClass

List of usage examples for java.lang.reflect Method getDeclaringClass

Introduction

In this page you can find the example usage for java.lang.reflect Method getDeclaringClass.

Prototype

@Override
public Class<?> getDeclaringClass() 

Source Link

Document

Returns the Class object representing the class or interface that declares the method represented by this object.

Usage

From source file:Main.java

/**
 * <p>//from  w  ww. j  av a 2 s. co m
 * Register a VTI.
 * </p>
 */
public static void registerVTI(Method method, String[] columnNames, String[] columnTypes, boolean readsSqlData)
        throws Exception {
    String methodName = method.getName();
    String sqlName = doubleQuote(methodName);
    Class methodClass = method.getDeclaringClass();
    Class[] parameterTypes = method.getParameterTypes();
    int parameterCount = parameterTypes.length;
    int columnCount = columnNames.length;
    StringBuilder buffer = new StringBuilder();

    buffer.append("create function ");
    buffer.append(sqlName);
    buffer.append("\n( ");
    for (int i = 0; i < parameterCount; i++) {
        if (i > 0) {
            buffer.append(", ");
        }

        String parameterType = mapType(parameterTypes[i]);

        buffer.append("arg");
        buffer.append(i);
        buffer.append(" ");
        buffer.append(parameterType);
    }
    buffer.append(" )\n");

    buffer.append("returns table\n");
    buffer.append("( ");
    for (int i = 0; i < columnCount; i++) {
        if (i > 0) {
            buffer.append(", ");
        }

        buffer.append("\"" + columnNames[i] + "\"");
        buffer.append(" ");
        buffer.append(columnTypes[i]);
    }
    buffer.append(" )\n");

    buffer.append("language java\n");
    buffer.append("parameter style DERBY_JDBC_RESULT_SET\n");
    if (readsSqlData) {
        buffer.append("reads sql data\n");
    } else {
        buffer.append("no sql\n");
    }

    buffer.append("external name ");
    buffer.append("'");
    buffer.append(methodClass.getName());
    buffer.append(".");
    buffer.append(methodName);
    buffer.append("'\n");

    executeDDL(buffer.toString());
}

From source file:org.dimitrovchi.conf.service.ServiceParameterUtils.java

@SuppressWarnings({ "element-type-mismatch" })
public static <P> P mergeAnnotationParameters() {
    final AnnotationParameters aParameters = annotationParameters();
    return (P) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
            aParameters.annotations.toArray(new Class[aParameters.annotations.size()]),
            new InvocationHandler() {
                @Override//  ww  w .  j  a v a 2s .c o m
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if ("toString".equals(method.getName())) {
                        return reflectToString(aParameters.topCaller.getSimpleName(), proxy);
                    }
                    final Class<?> annotationClass = method.getDeclaringClass();
                    final List<Annotation> annotations = aParameters.annotationMap.containsKey(annotationClass)
                            ? aParameters.annotationMap.get(annotationClass)
                            : Collections.<Annotation>emptyList();
                    for (final Annotation annotation : annotations) {
                        final Object value = method.invoke(annotation, args);
                        if (!Objects.deepEquals(method.getDefaultValue(), value)) {
                            return value;
                        }
                    }
                    return method.getDefaultValue();
                }
            });
}

From source file:com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBReflector.java

/**
 * Returns whether the method given is a getter method we should serialize /
 * deserialize to the service. The method must begin with "get" or "is",
 * have no arguments, belong to a class that declares its table, and not be
 * marked ignored./*from w  w w . j  a v  a 2s.c o m*/
 */
private static boolean isRelevantGetter(Method m) {
    return (m.getName().startsWith("get") || m.getName().startsWith("is")) && m.getParameterTypes().length == 0
            && isDocumentType(m.getDeclaringClass())
            && !ReflectionUtils.getterOrFieldHasAnnotation(m, DynamoDBIgnore.class);
}

From source file:org.caratarse.auth.model.util.BeanUtils.java

/**
 * Copy the not-null property values of the given source bean into the given target bean.
 * <p>/*from  w w  w.  j a v  a2  s  .  c om*/
 * Note: The source and target classes do not have to match or even be derived from each other,
 * as long as the properties match. Any bean properties that the source bean exposes but the
 * target bean does not will silently be ignored.
 *
 * @param source the source bean
 * @param target the target bean
 * @param editable the class (or interface) to restrict property setting to
 * @param ignoreProperties array of property names to ignore
 * @throws BeansException if the copying failed
 * @see BeanWrapper
 */
private static void copyNotNullProperties(Object source, Object target, Class<?> editable,
        String... ignoreProperties) throws BeansException {

    Assert.notNull(source, "Source must not be null");
    Assert.notNull(target, "Target must not be null");

    Class<?> actualEditable = target.getClass();
    if (editable != null) {
        if (!editable.isInstance(target)) {
            throw new IllegalArgumentException("Target class [" + target.getClass().getName()
                    + "] not assignable to Editable class [" + editable.getName() + "]");
        }
        actualEditable = editable;
    }
    PropertyDescriptor[] targetPds = org.springframework.beans.BeanUtils.getPropertyDescriptors(actualEditable);
    List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);

    for (PropertyDescriptor targetPd : targetPds) {
        Method writeMethod = targetPd.getWriteMethod();
        if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
            PropertyDescriptor sourcePd = org.springframework.beans.BeanUtils
                    .getPropertyDescriptor(source.getClass(), targetPd.getName());
            if (sourcePd != null) {
                Method readMethod = sourcePd.getReadMethod();
                if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0],
                        readMethod.getReturnType())) {
                    try {
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                            readMethod.setAccessible(true);
                        }
                        Object value = readMethod.invoke(source);
                        if (value == null) {
                            continue;
                        }
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            writeMethod.setAccessible(true);
                        }
                        writeMethod.invoke(target, value);
                    } catch (Throwable ex) {
                        throw new FatalBeanException(
                                "Could not copy property '" + targetPd.getName() + "' from source to target",
                                ex);
                    }
                }
            }
        }
    }
}

From source file:nl.strohalm.cyclos.utils.EntityHelper.java

/**
 * Returns a Map with basic properties for the given entity
 *//*from w ww.ja va2  s.c o m*/
public static Map<String, PropertyDescriptor> propertyDescriptorsFor(final Entity entity) {
    final Class<? extends Entity> clazz = getRealClass(entity);
    SortedMap<String, PropertyDescriptor> properties = cachedPropertiesByClass.get(clazz);
    if (properties == null) {
        properties = new TreeMap<String, PropertyDescriptor>();
        final PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(clazz);
        for (final PropertyDescriptor descriptor : propertyDescriptors) {
            final String name = descriptor.getName();
            boolean ok = name.equals("id");
            if (!ok) {
                final Method readMethod = descriptor.getReadMethod();
                if (readMethod != null) {
                    final Class<?> declaringClass = readMethod.getDeclaringClass();
                    ok = !declaringClass.equals(Entity.class)
                            && !declaringClass.equals(CustomFieldsContainer.class);
                }
            }
            if (ok) {
                properties.put(name, descriptor);
            }
        }
        properties = Collections.unmodifiableSortedMap(properties);
        cachedPropertiesByClass.put(clazz, properties);
    }
    return properties;
}

From source file:org.apache.sling.scripting.sightly.impl.compiler.CompileTimeObjectModel.java

private static Method getClassMethod(Class<?> clazz, Method m) {
    Method mp;
    try {/*from w ww .j  a  v  a2s .  c  o  m*/
        mp = clazz.getMethod(m.getName(), m.getParameterTypes());
        mp = extractMethodInheritanceChain(mp.getDeclaringClass(), mp);
        if (mp != null) {
            return mp;
        }
    } catch (NoSuchMethodException e) {
        // do nothing
    }
    return null;
}

From source file:com.linecorp.armeria.server.docs.FunctionInfo.java

static FunctionInfo of(Method method, Map<Class<?>, ? extends TBase<?, ?>> sampleRequests,
        @Nullable String namespace, Map<String, String> docStrings) throws ClassNotFoundException {
    requireNonNull(method, "method");

    final String methodName = method.getName();

    final Class<?> serviceClass = method.getDeclaringClass().getDeclaringClass();
    final String serviceName = serviceClass.getName();
    final ClassLoader classLoader = serviceClass.getClassLoader();

    @SuppressWarnings("unchecked")
    Class<? extends TBase<?, ?>> argsClass = (Class<? extends TBase<?, ?>>) Class
            .forName(serviceName + '$' + methodName + "_args", false, classLoader);
    String sampleJsonRequest;//w  ww.j  a v  a  2 s  . co m
    TBase<?, ?> sampleRequest = sampleRequests.get(argsClass);
    if (sampleRequest == null) {
        sampleJsonRequest = "";
    } else {
        TSerializer serializer = new TSerializer(ThriftProtocolFactories.TEXT);
        try {
            sampleJsonRequest = serializer.toString(sampleRequest, StandardCharsets.UTF_8.name());
        } catch (TException e) {
            throw new IllegalArgumentException(
                    "Failed to serialize to a memory buffer, this shouldn't ever happen.", e);
        }
    }

    @SuppressWarnings("unchecked")
    final FunctionInfo function = new FunctionInfo(namespace, methodName, argsClass,
            (Class<? extends TBase<?, ?>>) Class.forName(serviceName + '$' + methodName + "_result", false,
                    classLoader),
            (Class<? extends TException>[]) method.getExceptionTypes(), sampleJsonRequest, docStrings);
    return function;
}

From source file:org.zht.framework.util.ZBeanUtil.java

private static void copy(Object source, Object target, Boolean ignorNull, Class<?> editable,
        String... ignoreProperties) throws BeansException {

    Assert.notNull(source, "Source must not be null");
    Assert.notNull(target, "Target must not be null");

    Class<?> actualEditable = target.getClass();
    if (editable != null) {
        if (!editable.isInstance(target)) {
            throw new IllegalArgumentException("Target class [" + target.getClass().getName()
                    + "] not assignable to Editable class [" + editable.getName() + "]");
        }/*from w  ww.  j ava 2 s . c  o m*/
        actualEditable = editable;
    }
    PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
    List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);

    for (PropertyDescriptor targetPd : targetPds) {
        Method writeMethod = targetPd.getWriteMethod();
        if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
            PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
            if (sourcePd != null) {
                Method readMethod = sourcePd.getReadMethod();
                if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0],
                        readMethod.getReturnType())) {
                    try {
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                            readMethod.setAccessible(true);
                        }
                        Object value = readMethod.invoke(source);
                        if (ignorNull != null && ignorNull) {
                            if (value != null && (!"[]".equals(value.toString()))) {// ?
                                if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                    writeMethod.setAccessible(true);
                                }
                                writeMethod.invoke(target, value);
                            }
                        } else {
                            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                writeMethod.setAccessible(true);
                            }
                            writeMethod.invoke(target, value);
                        }

                    } catch (Throwable ex) {
                        throw new FatalBeanException(
                                "Could not copy property '" + targetPd.getName() + "' from source to target",
                                ex);
                    }
                }
            }
        }
    }
}

From source file:ch.ralscha.extdirectspring.util.MethodInfo.java

/**
 * Find a method that is annotated with a specific annotation. Starts with the method
 * and goes up to the superclasses of the class.
 *
 * @param method the starting method/*from  ww  w .jav a2s  .c o m*/
 * @param annotation the annotation to look for
 * @return the method if there is a annotated method, else null
 */
public static Method findMethodWithAnnotation(Method method, Class<? extends Annotation> annotation) {
    if (method.isAnnotationPresent(annotation)) {
        return method;
    }

    Class<?> cl = method.getDeclaringClass();
    while (cl != null && cl != Object.class) {
        try {
            Method equivalentMethod = cl.getDeclaredMethod(method.getName(), method.getParameterTypes());
            if (equivalentMethod.isAnnotationPresent(annotation)) {
                return equivalentMethod;
            }
        } catch (NoSuchMethodException e) {
            // do nothing here
        }
        cl = cl.getSuperclass();
    }

    return null;
}

From source file:com.link_intersystems.lang.reflect.Method2.java

/**
 *
 * @param method/*from w w  w  .  j  a  v a  2 s.c o m*/
 * @return a {@link Method2} object for the given {@link Method}.
 * @since 1.0.0.0
 */
public static Method2 forMethod(Method method) {
    Assert.notNull("method", method);
    Class<?> declaringClass = method.getDeclaringClass();
    Class2<?> declaringClass2 = Class2.get(declaringClass);
    Method2 method2;
    try {
        method2 = declaringClass2.getMethod2(method);
        return method2;
    } catch (NoSuchMethodException e) {
        throw new IllegalStateException("Implementation error.", e);
    }
}