Example usage for java.lang.reflect Constructor isAccessible

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

Introduction

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

Prototype

@Deprecated(since = "9")
public boolean isAccessible() 

Source Link

Document

Get the value of the accessible flag for this reflected object.

Usage

From source file:at.ac.tuwien.infosys.jcloudscale.classLoader.caching.fileCollectors.FileCollectorAbstract.java

/**
 * Collects the list of required files without content.
 * @param clazz the class that related files should be collected for. (joda style)
 * @return List of files that are required for specified class or 
 * null if none are required. /*from   w  ww  .  ja v a 2 s  .co m*/
 */
protected List<ClassLoaderFile> collectRequiredFiles(Class<?> clazz) {
    FileDependency fileDependency = clazz.getAnnotation(FileDependency.class);

    if (fileDependency == null)
        return null;

    List<ClassLoaderFile> files = new ArrayList<ClassLoaderFile>();

    if (fileDependency.dependencyProvider().equals(IFileDependencyProvider.class)) {// we have static files
        //         ContentType contentType = fileDependency.accessType() == FileAccess.ReadOnly ? 
        //                                    ContentType.ROFILE : ContentType.RWFILE;
        ContentType contentType = ContentType.ROFILE;

        String[] fileNames = fileDependency.files();

        if (fileNames == null || fileNames.length == 0)
            return null;

        for (String filename : fileNames) {
            File file = RemoteClassLoaderUtils.getRelativePathFile(filename);
            if (!file.exists()) {
                log.severe("Class " + clazz.getName() + " set file " + filename
                        + " as required, but the file is missing at " + file.getAbsolutePath());
                continue;
            }

            files.add(new ClassLoaderFile(filename, file.lastModified(), file.length(), contentType));
        }
    } else {// we have dynamic file list, let's process it.
        Class<? extends IFileDependencyProvider> dependentFilesProviderClass = fileDependency
                .dependencyProvider();
        if (dependentFilesProviderClass == null)
            return null;

        //checking if we can create this class
        if (dependentFilesProviderClass.isInterface()
                || Modifier.isAbstract(dependentFilesProviderClass.getModifiers()))
            throw new JCloudScaleException("Class " + clazz.getName()
                    + "is anotated with @FileDependency and has class " + dependentFilesProviderClass.getName()
                    + " as dependency provider. However, dependency provider class is either abstract or interface.");

        if (dependentFilesProviderClass.getEnclosingClass() != null
                && !Modifier.isStatic(dependentFilesProviderClass.getModifiers()))
            throw new JCloudScaleException("Class " + clazz.getName()
                    + "is anotated with @FileDependency and has class " + dependentFilesProviderClass.getName()
                    + " as dependency provider. However, dependency provider class is internal and not static. The class has to be static in this case.");

        Constructor<? extends IFileDependencyProvider> constructor = null;
        try {
            constructor = dependentFilesProviderClass.getDeclaredConstructor();
        } catch (NoSuchMethodException ex) {
            throw new JCloudScaleException(ex, "Class " + clazz.getName()
                    + "is anotated with @FileDependency and has class " + dependentFilesProviderClass.getName()
                    + " as dependency provider. However, dependency provider class cannot be created as it has no parameterless constructor.");
        }

        try {
            if (!constructor.isAccessible())
                constructor.setAccessible(true);

            IFileDependencyProvider provider = constructor.newInstance();

            for (DependentFile dependentFile : provider.getDependentFiles()) {
                File file = RemoteClassLoaderUtils.getRelativePathFile(dependentFile.filePath);
                if (!file.exists()) {
                    log.severe("Class " + clazz.getName() + " set file " + dependentFile.filePath
                            + " as required, but the file is missing.");
                    continue;
                }

                //               ContentType contentType = dependentFile.accessType == FileAccess.ReadOnly ? 
                //                     ContentType.ROFILE : ContentType.RWFILE;
                ContentType contentType = ContentType.ROFILE;

                files.add(new ClassLoaderFile(file.getPath(), file.lastModified(), file.length(), contentType));
            }
        } catch (Exception ex) {
            log.severe("Dependent files provider " + dependentFilesProviderClass.getName() + " for class "
                    + clazz.getName() + " threw exception during execution:" + ex.toString());
            throw new JCloudScaleException(ex,
                    "Dependent files provider " + dependentFilesProviderClass.getName() + " for class "
                            + clazz.getName() + " threw exception during execution.");
        }
    }

    return files;
}

From source file:com.helpinput.utils.Utils.java

public static <T> Constructor<?> findConstructor(Class<T> targetClass, Class<?>[] agrsClasses) {
    Constructor<?>[] constructors = targetClass.getDeclaredConstructors();
    Constructor<?> theConstructor = null;

    for (Constructor<?> constructor : constructors) {
        Class<?>[] classes = constructor.getParameterTypes();
        if (agrsClasses.length == 0 && classes.length == 0) {
            theConstructor = constructor;
            break;
        }/*from   ww w .  j  a  va2 s .  c  om*/

        if (agrsClasses.length == classes.length) {
            for (int i = 0; i < agrsClasses.length; i++) {
                if (agrsClasses[i] == null) {
                    if (i == agrsClasses.length - 1) {
                        theConstructor = constructor;
                        break;
                    }
                    continue;
                }

                if (classes[i].isPrimitive()) {
                    if (!primitiveWrap(classes[i]).isAssignableFrom(agrsClasses[i]))
                        break;
                } else if (!classes[i].isAssignableFrom(agrsClasses[i]))
                    break;
                if (i == agrsClasses.length - 1) {
                    theConstructor = constructor;
                    break;
                }
            }
        }
        if (theConstructor != null)
            break;
    }

    if (null != theConstructor) {
        if (!theConstructor.isAccessible())
            theConstructor.setAccessible(true);
        return theConstructor;
    } else {
        if (targetClass.getSuperclass() != null) {
            return findConstructor(targetClass.getSuperclass(), agrsClasses);
        }
        return null;
    }
}

From source file:dinistiq.Dinistiq.java

/**
 * Creates an instance of the given type and registeres it with the container.
 *
 * @param dependencies dependencies within the scope
 * @param cls type to create an instance of
 * @param beanName beans name in the scope using the given dependencies
 *//*from   w  w w  . j a v  a 2  s . co  m*/
private <T extends Object> T createInstance(Map<String, Set<Object>> dependencies, Class<T> cls,
        String beanName) throws Exception {
    LOG.info("createInstance({})", cls.getSimpleName());
    Constructor<?> c = null;
    Constructor<?>[] constructors = cls.getDeclaredConstructors();
    LOG.debug("createInstance({}) constructors.length={}", cls.getSimpleName(), constructors.length);
    for (Constructor<?> ctor : constructors) {
        LOG.debug("createInstance({}) {}", cls.getSimpleName(), ctor);
        c = (ctor.getAnnotation(Inject.class) != null) ? ctor : c;
    } // for
    c = (c == null) ? cls.getConstructor() : c;
    // Don't record constructor dependencies - they MUST be already fulfilled
    Object[] parameters = getParameters(null, null, beanName, c.getParameterTypes(),
            c.getGenericParameterTypes(), c.getParameterAnnotations());
    dependencies.put(beanName, new HashSet<>());
    boolean accessible = c.isAccessible();
    try {
        c.setAccessible(true);
        return convert(c.newInstance(parameters));
    } finally {
        c.setAccessible(accessible);
    } // try/finally
}

From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java

/**
 * Returns a {@link Constructor} object that reflects the specified constructor of the given type.
 * <p/>//  www  . ja  va 2  s  .c o  m
 * If no parameter types are specified i.e., {@code paramTypes} is {@code null} or empty, the default constructor
 * is returned.<br/>
 * If a parameter type is not known i.e., it is {@code null}, all declared constructors are checked whether their
 * parameter types conform to the known parameter types i.e., if every known type is assignable to the parameter
 * type of the constructor and if exactly one was found, it is returned.<br/>
 * Otherwise a {@link NoSuchMethodException} is thrown indicating that no or several constructors were found.
 *
 * @param type the class
 * @param paramTypes the full-qualified class names of the parameters (can be {@code null})
 * @param classLoader the class loader to use
 * @return the accessible constructor resolved
 * @throws NoSuchMethodException if there are zero or more than one constructor candidates
 * @throws ClassNotFoundException if a class cannot be located by the specified class loader
 */
@SuppressWarnings("unchecked")
public static <T> Constructor<T> findConstructor(Class<T> type, Class<?>... clazzes)
        throws NoSuchMethodException, ClassNotFoundException {
    Constructor<T> constructor = null;

    // If all parameter types are known, find the constructor that exactly matches the signature
    if (!ArrayUtils.contains(clazzes, null)) {
        try {
            constructor = type.getDeclaredConstructor(clazzes);
        } catch (NoSuchMethodException e) {
            // Ignore
        }
    }

    // If no constructor was found, find all possible candidates
    if (constructor == null) {
        List<Constructor<T>> candidates = new ArrayList<>(1);
        for (Constructor<T> declaredConstructor : (Constructor<T>[]) type.getDeclaredConstructors()) {
            if (ClassUtils.isAssignable(clazzes, declaredConstructor.getParameterTypes())) {

                // Check if there is already a constructor method with the same signature
                for (int i = 0; i < candidates.size(); i++) {
                    Constructor<T> candidate = candidates.get(i);
                    /**
                     * If all parameter types of constructor A are assignable to the types of constructor B
                     * (at least one type is a subtype of the corresponding parameter), keep the one whose types
                     * are more concrete and drop the other one.
                     */
                    if (ClassUtils.isAssignable(declaredConstructor.getParameterTypes(),
                            candidate.getParameterTypes())) {
                        candidates.remove(candidate);
                        i--;
                    } else if (ClassUtils.isAssignable(candidate.getParameterTypes(),
                            declaredConstructor.getParameterTypes())) {
                        declaredConstructor = null;
                        break;
                    }
                }

                if (declaredConstructor != null) {
                    candidates.add(declaredConstructor);
                }
            }
        }
        if (candidates.size() != 1) {
            throw new NoSuchMethodException(
                    String.format("Cannot find distinct constructor for type '%s' with parameter types %s",
                            type, Arrays.toString(clazzes)));
        }
        constructor = candidates.get(0);
    }

    //do we really need this dependency?
    //ReflectionUtils.makeAccessible(constructor);
    if (constructor != null && !constructor.isAccessible())
        constructor.setAccessible(true);

    return constructor;

}