Example usage for java.lang.reflect Constructor getDeclaringClass

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

Introduction

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

Prototype

@Override
public Class<T> getDeclaringClass() 

Source Link

Document

Returns the Class object representing the class that declares the constructor represented by this object.

Usage

From source file:br.com.lucasisrael.regra.reflections.TratamentoReflections.java

/**
 * Make the given constructor accessible, explicitly setting it accessible
 * if necessary. The {@code setAccessible(true)} method is only called
 * when actually necessary, to avoid unnecessary conflicts with a JVM
 * SecurityManager (if active)./*w  w w. j  ava 2 s  . c o  m*/
 * @param ctor the constructor to make accessible
 * @see java.lang.reflect.Constructor#setAccessible
 */
public static void makeAccessible(Constructor<?> ctor) {
    if ((!Modifier.isPublic(ctor.getModifiers()) || !Modifier.isPublic(ctor.getDeclaringClass().getModifiers()))
            && !ctor.isAccessible()) {
        ctor.setAccessible(true);
    }
}

From source file:org.eclipse.wb.internal.core.model.description.helpers.ComponentDescriptionHelper.java

/**
 * TODO move into {@link ReflectionUtils}.
 * //from   w  w w.  j  a v  a2s. c om
 * @return the source for creating {@link Object} using given {@link Constructor} with values
 *         default for type of each argument.
 */
public static String getDefaultConstructorInvocation(Constructor<?> constructor) {
    // prepare Class
    Class<?> componentClass = constructor.getDeclaringClass();
    String componentClassName = ReflectionUtils.getCanonicalName(componentClass);
    // prepare arguments
    String arguments;
    {
        StringBuilder buffer = new StringBuilder();
        for (Class<?> parameter : constructor.getParameterTypes()) {
            String parameterName = ReflectionUtils.getCanonicalName(parameter);
            buffer.append(AstParser.getDefaultValue(parameterName));
            buffer.append(", ");
        }
        arguments = StringUtils.removeEnd(buffer.toString(), ", ");
    }
    // prepare source
    return "new " + componentClassName + "(" + arguments + ")";
}

From source file:org.springframework.beans.BeanUtils.java

/**
 * Convenience method to instantiate a class using the given constructor.
 * <p>Note that this method tries to set the constructor accessible if given a
 * non-accessible (that is, non-public) constructor, and supports Kotlin classes
 * with optional parameters and default values.
 * @param ctor the constructor to instantiate
 * @param args the constructor arguments to apply (use {@code null} for an unspecified
 * parameter if needed for Kotlin classes with optional parameters and default values)
 * @return the new instance/*from  w ww  . j  a v  a  2s .c  om*/
 * @throws BeanInstantiationException if the bean cannot be instantiated
 * @see Constructor#newInstance
 */
public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {
    Assert.notNull(ctor, "Constructor must not be null");
    try {
        ReflectionUtils.makeAccessible(ctor);
        return (KotlinDetector.isKotlinType(ctor.getDeclaringClass())
                ? KotlinDelegate.instantiateClass(ctor, args)
                : ctor.newInstance(args));
    } catch (InstantiationException ex) {
        throw new BeanInstantiationException(ctor, "Is it an abstract class?", ex);
    } catch (IllegalAccessException ex) {
        throw new BeanInstantiationException(ctor, "Is the constructor accessible?", ex);
    } catch (IllegalArgumentException ex) {
        throw new BeanInstantiationException(ctor, "Illegal arguments for constructor", ex);
    } catch (InvocationTargetException ex) {
        throw new BeanInstantiationException(ctor, "Constructor threw exception", ex.getTargetException());
    }
}

From source file:ca.oson.json.util.ObjectUtil.java

/**
 * Returns a list containing one parameter name for each argument accepted
 * by the given constructor. If the class was compiled with debugging
 * symbols, the parameter names will match those provided in the Java source
 * code. Otherwise, a generic "arg" parameter name is generated ("arg0" for
 * the first argument, "arg1" for the second...).
 *
 * This method relies on the constructor's class loader to locate the
 * bytecode resource that defined its class.
 *
 * @param constructor the constructor to get a list of parameter names
 * @return a list of parameter names//  w  ww  .  j a  v a  2  s  . com
 * @throws IOException io exception to throw
 */
private static List<String> getParameterNamesBytecode(Constructor<?> constructor) throws IOException {
    Class<?> declaringClass = constructor.getDeclaringClass();
    ClassLoader declaringClassLoader = declaringClass.getClassLoader();

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

    org.objectweb.asm.Type declaringType = org.objectweb.asm.Type.getType(declaringClass);
    String constructorDescriptor = org.objectweb.asm.Type.getConstructorDescriptor(constructor);
    String url = declaringType.getInternalName() + ".class";

    InputStream classFileInputStream = declaringClassLoader.getResourceAsStream(url);
    if (classFileInputStream == null) {
        // throw new IllegalArgumentException("The constructor's class loader cannot find the bytecode that defined the constructor's class (URL: " + url + ")");
        return null;
    }

    ClassNode classNode;
    try {
        classNode = new ClassNode();
        ClassReader classReader = new ClassReader(classFileInputStream);
        classReader.accept(classNode, 0);
    } finally {
        classFileInputStream.close();
    }

    @SuppressWarnings("unchecked")
    List<MethodNode> methods = classNode.methods;
    for (MethodNode method : methods) {
        if (method.name.equals("<init>") && method.desc.equals(constructorDescriptor)) {
            org.objectweb.asm.Type[] argumentTypes = org.objectweb.asm.Type.getArgumentTypes(method.desc);
            List<String> parameterNames = new ArrayList<String>(argumentTypes.length);

            @SuppressWarnings("unchecked")
            List<LocalVariableNode> localVariables = method.localVariables;
            for (int i = 0; i < argumentTypes.length && i < localVariables.size() - 1; i++) {
                // The first local variable actually represents the "this" object
                parameterNames.add(localVariables.get(i + 1).name);
            }

            return parameterNames;
        }
    }

    return null;
}

From source file:co.jirm.mapper.definition.SqlParameterDefinition.java

private static Map<String, SqlParameterDefinition> getSqlBeanParametersFromJsonCreatorConstructor(
        Constructor<?> c, SqlObjectConfig config) {
    Map<String, SqlParameterDefinition> parameters = new LinkedHashMap<String, SqlParameterDefinition>();
    Annotation[][] aas = c.getParameterAnnotations();
    Class<?>[] pts = c.getParameterTypes();
    if (aas == null || aas.length == 0) {
        return parameters;
    }/*from   w  w w . ja v a  2 s.  c  o  m*/

    for (int i = 0; i < aas.length; i++) {
        Annotation[] as = aas[i];
        Class<?> parameterType = pts[i];
        for (int j = 0; j < as.length; j++) {
            Annotation a = as[j];
            if (JsonProperty.class.equals(a.annotationType())) {
                JsonProperty p = (JsonProperty) a;
                String value = p.value();
                final SqlParameterDefinition definition = parameterDef(config, c.getDeclaringClass(), value,
                        parameterType, i);
                parameters.put(value, definition);
            }
        }

    }

    return parameters;
}

From source file:net.abhinavsarkar.spelhelper.ImplicitConstructorResolver.java

@Override
public ConstructorExecutor resolve(final EvaluationContext context, final String typeName,
        final List<TypeDescriptor> argumentTypes) throws AccessException {
    try {/* w w w .  j  a v  a  2  s .  c o m*/
        return delegate.resolve(context, typeName, argumentTypes);
    } catch (AccessException ex) {
        Object variable = ((SpelHelper) context.lookupVariable(SpelHelper.CONTEXT_LOOKUP_KEY))
                .lookupImplicitConstructor(typeName + argumentTypes.toString());
        if (variable instanceof Constructor<?>) {
            Constructor<?> constructor = (Constructor<?>) variable;
            return delegate.resolve(context, constructor.getDeclaringClass().getName(), argumentTypes);
        }
        return null;
    }
}

From source file:org.batoo.common.reflect.ReflectHelper.java

private static ConstructorAccessor createConstructorImpl(Constructor<?> constructor) {
    try {/*from  w  w  w. ja v  a 2 s.c  o  m*/
        final Class<?> magClass = Class.forName("sun.reflect.MethodAccessorGenerator");
        final Constructor<?> c = magClass.getDeclaredConstructors()[0];
        final Method generateMethod = magClass.getMethod("generateConstructor", Class.class, Class[].class,
                Class[].class, Integer.TYPE);

        ReflectHelper.setAccessible(c, true);
        ReflectHelper.setAccessible(generateMethod, true);

        try {
            final Object mag = c.newInstance();

            return new SunConstructorAccessor(
                    generateMethod.invoke(mag, constructor.getDeclaringClass(), constructor.getParameterTypes(),
                            constructor.getExceptionTypes(), constructor.getModifiers()));
        } finally {
            ReflectHelper.setAccessible(c, false);
            ReflectHelper.setAccessible(generateMethod, false);
        }
    } catch (final Exception e) {
        throw new RuntimeException("Constructor generation failed", e);
    }
}

From source file:org.brutusin.instrumentation.logging.LoggingInterceptor.java

private File getFile(Object source, String executionId) {
    String loggingFolderPath = "JVM-" + ManagementFactory.getRuntimeMXBean().getStartTime() + "/"
            + Thread.currentThread().getName() + "-" + Thread.currentThread().getId() + "/" + executionId + "-";
    if (source instanceof Method) {
        Method m = (Method) source;
        loggingFolderPath += m.getDeclaringClass().getName() + "." + m.getName() + "()";
    } else if (source instanceof Constructor) {
        Constructor c = (Constructor) source;
        String className = c.getDeclaringClass().getName();
        if (className != null && className.length() > 0) {
            loggingFolderPath += className + ".init()";
        } else {/*from w w  w  .jav  a2 s .  c o m*/
            loggingFolderPath += "init()";
        }
    } else {
        loggingFolderPath += source;
    }
    loggingFolderPath += ".log";
    loggingFolderPath = loggingFolderPath.replaceAll("[<>:]", "-");
    File ret = new File(rootFile, loggingFolderPath);
    try {
        FileUtils.forceMkdir(ret.getParentFile());
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    return ret;
}

From source file:org.springframework.core.LocalVariableTableParameterNameDiscoverer.java

@Override
@Nullable/* w w  w.  ja  v a2 s . c o  m*/
public String[] getParameterNames(Constructor<?> ctor) {
    Class<?> declaringClass = ctor.getDeclaringClass();
    Map<Member, String[]> map = this.parameterNamesCache.get(declaringClass);
    if (map == null) {
        map = inspectClass(declaringClass);
        this.parameterNamesCache.put(declaringClass, map);
    }
    if (map != NO_DEBUG_INFO_MAP) {
        return map.get(ctor);
    }
    return null;
}

From source file:com.quirklabs.authorise.ProxyAwareLocalVariableTableParameterNameDiscoverer.java

/**
 * Visit the given constructor and discover its parameter names.
 *//* w  ww  .j a va 2  s. com*/
private ParameterNameDiscoveringVisitor visitConstructor(Constructor ctor) throws IOException {
    ClassReader classReader = getClassReader(ctor.getDeclaringClass());
    FindConstructorParameterNamesClassVisitor classVisitor = new FindConstructorParameterNamesClassVisitor(
            ctor);
    classReader.accept(classVisitor, 0);
    return classVisitor;
}