Example usage for java.lang.reflect Method isAccessible

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

Introduction

In this page you can find the example usage for java.lang.reflect Method 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:name.yumaa.ChromeLogger4J.java

/**
 * Converts an object to a better format for logging
 * @param object    variable to conver//from   w w w . j a  v  a 2  s  .  c  o  m
 * @param depth     recursion depth
 * @return converted object, ready to put to JSON
 */
private Object convert(Object object, int depth) {
    // *** return simple types as is ***
    if (object == null || object instanceof String || object instanceof Number || object instanceof Boolean)
        return object;

    // *** other simple types ***

    if (object instanceof Character || object instanceof StringBuffer || object instanceof StringBuilder
            || object instanceof Currency || object instanceof Date || object instanceof Locale)
        return object.toString();

    if (object instanceof Calendar)
        return ((Calendar) object).getTime().toString();

    if (object instanceof SimpleDateFormat)
        return ((SimpleDateFormat) object).toPattern();

    // check recursion depth
    if (depth > this.depth)
        return "d>" + this.depth;

    // mark this object as processed so we don't convert it twice and it
    // also avoid recursion when objects refer to each other
    processed.add(object);

    // *** not so simple types, but we can foreach it ***

    if (object instanceof Map) {
        JSONObject jobject = new JSONObject();
        for (Object key : ((Map<Object, Object>) object).keySet()) {
            Object value = ((Map<Object, Object>) object).get(key);
            addValue(jobject, key.toString(), value, depth);
        }
        return jobject;
    }

    if (object instanceof Collection) {
        JSONArray jobject = new JSONArray();
        for (Object value : (Collection<Object>) object)
            addValue(jobject, value, depth);
        return jobject;
    }

    if (object instanceof Iterable) {
        JSONArray jobject = new JSONArray();
        for (Object value : (Iterable<Object>) object)
            addValue(jobject, value, depth);
        return jobject;
    }

    if (object instanceof Object[]) {
        JSONArray jobject = new JSONArray();
        for (Object value : (Object[]) object)
            addValue(jobject, value, depth);
        return jobject;
    }

    // *** object of unknown type ***

    JSONObject jobject = new JSONObject();

    Class<?> cls = object.getClass();
    jobject.put("___class_name", cls.getName()); // add the class name
    jobject.put("___toString()", object.toString()); // and to string representation

    if (!this.reflect)
        return jobject;

    // get all properties using reflection
    if (this.reflectfields) {
        try {
            for (Field field : cls.getDeclaredFields()) {
                Boolean access = field.isAccessible();
                field.setAccessible(true);

                int mod = field.getModifiers();
                String key = getKey(mod, field.getName());
                Object value;
                try {
                    value = field.get(object);
                } catch (Exception e) {
                    value = e.toString();
                }

                field.setAccessible(access);

                if (!this.reflectprivate && (Modifier.isPrivate(mod) || Modifier.isProtected(mod)))
                    continue;
                if (!this.reflectstatic && Modifier.isStatic(mod))
                    continue;

                addValue(jobject, key, value, depth);
            }
        } catch (SecurityException e) {
        }
    }

    // get all methods using reflection
    if (this.reflectmethods) {
        try {
            JSONObject methods = new JSONObject();
            for (Method method : cls.getDeclaredMethods()) {
                Boolean access = method.isAccessible();
                method.setAccessible(true);

                Class<?>[] params = method.getParameterTypes();
                StringBuilder parameters = new StringBuilder("");
                for (int i = 0, j = params.length; i < j; i++) {
                    parameters.append(params[i].getName());
                    if (i + 1 < j)
                        parameters.append(", ");
                }
                int mod = method.getModifiers();
                String key = getKey(mod, method.getName() + "(" + parameters.toString() + ")");
                String value = method.getReturnType().getName();

                method.setAccessible(access);

                if (!this.reflectprivate && (Modifier.isPrivate(mod) || Modifier.isProtected(mod)))
                    continue;
                if (!this.reflectstatic && Modifier.isStatic(mod))
                    continue;

                methods.put(key, value);
            }
            jobject.put("___methods", methods);
        } catch (SecurityException e) {
        }
    }

    return jobject;
}

From source file:org.openmrs.module.sync.SyncUtil.java

public static void setProperty(Object o, String propName, Object propVal)
        throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    Object[] setterParams = new Object[] { propVal };

    log.debug("getting setter method");
    Method m = SyncUtil.getSetterMethod(o.getClass(), propName, propVal.getClass());
    if (m == null) {
        // We couldn't find a setter method. Let's try setting the field directly instead.
        log.debug("couldn't find setter method, setting field '" + propName + "' directly.");
        FieldUtils.writeField(o, propName, propVal, true);
        return;/*  w w  w . j av a 2s .c  om*/
    }

    boolean acc = m.isAccessible();
    m.setAccessible(true);
    log.debug("about to call " + m.getName());
    try {
        m.invoke(o, setterParams);
    } finally {
        m.setAccessible(acc);
    }
}

From source file:com.p5solutions.core.utils.ReflectionUtility.java

/**
 * Make accessible./*from  w ww  .j av  a2s. c  o  m*/
 * 
 * @param method
 *          the method
 * @return true, if successful
 */
public static boolean makeAccessible(Method method) {
    boolean original = method.isAccessible();
    if (!original) {
        method.setAccessible(true);
    }
    return original;
}

From source file:org.apache.axis2.jaxws.lifecycle.BaseLifecycleManager.java

protected void invokePostConstruct(final Method method) throws LifecycleException {
    if (log.isDebugEnabled()) {
        log.debug("Invoking Method with @PostConstruct annotation");
    }//from w w  w. j av a2  s. c o  m
    /*
     * As per JSR-250 pre destroy and post construct can be
     * public, protected, private or default encapsulation.
     * I will check and make sure the methods are accessible
     * before we invoke them.
     * 
     */

    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws InvocationTargetException, IllegalAccessException {
                if (!method.isAccessible()) {
                    method.setAccessible(true);
                }
                return null;
            }
        });
    } catch (PrivilegedActionException e) {
        throw new LifecycleException(e.getException());
    }
    invokeMethod(method, null);
    if (log.isDebugEnabled()) {
        log.debug("Completed invoke on Method with @PostConstruct annotation");
    }
}

From source file:org.apache.tomee.embedded.TomEEEmbeddedApplicationRunner.java

public synchronized void start(final Class<?> marker, final Properties config, final String... args)
        throws Exception {
    if (started) {
        return;/*from  ww w  . j ava 2  s .com*/
    }

    ensureAppInit(marker);
    started = true;

    final Class<?> appClass = app.getClass();
    final AnnotationFinder finder = new AnnotationFinder(new ClassesArchive(ancestors(appClass)));

    // setup the container config reading class annotation, using a randome http port and deploying the classpath
    final Configuration configuration = new Configuration();
    final ContainerProperties props = appClass.getAnnotation(ContainerProperties.class);
    if (props != null) {
        final Properties runnerProperties = new Properties();
        for (final ContainerProperties.Property p : props.value()) {
            final String name = p.name();
            if (name.startsWith("tomee.embedded.application.runner.")) { // allow to tune the Configuration
                // no need to filter there since it is done in loadFromProperties()
                runnerProperties.setProperty(name.substring("tomee.embedded.application.runner.".length()),
                        p.value());
            } else {
                configuration.property(name, StrSubstitutor.replaceSystemProperties(p.value()));
            }
        }
        if (!runnerProperties.isEmpty()) {
            configuration.loadFromProperties(runnerProperties);
        }
    }
    configuration.loadFromProperties(System.getProperties()); // overrides, note that some config are additive by design

    final List<Method> annotatedMethods = finder
            .findAnnotatedMethods(org.apache.openejb.testing.Configuration.class);
    if (annotatedMethods.size() > 1) {
        throw new IllegalArgumentException("Only one @Configuration is supported: " + annotatedMethods);
    }
    for (final Method m : annotatedMethods) {
        final Object o = m.invoke(app);
        if (Properties.class.isInstance(o)) {
            final Properties properties = Properties.class.cast(o);
            if (configuration.getProperties() == null) {
                configuration.setProperties(new Properties());
            }
            configuration.getProperties().putAll(properties);
        } else {
            throw new IllegalArgumentException("Unsupported " + o + " for @Configuration");
        }
    }

    final Collection<org.apache.tomee.embedded.LifecycleTask> lifecycleTasks = new ArrayList<>();
    final Collection<Closeable> postTasks = new ArrayList<>();
    final LifecycleTasks tasks = appClass.getAnnotation(LifecycleTasks.class);
    if (tasks != null) {
        for (final Class<? extends org.apache.tomee.embedded.LifecycleTask> type : tasks.value()) {
            final org.apache.tomee.embedded.LifecycleTask lifecycleTask = type.newInstance();
            lifecycleTasks.add(lifecycleTask);
            postTasks.add(lifecycleTask.beforeContainerStartup());
        }
    }

    final Map<String, Field> ports = new HashMap<>();
    {
        Class<?> type = appClass;
        while (type != null && type != Object.class) {
            for (final Field f : type.getDeclaredFields()) {
                final RandomPort annotation = f.getAnnotation(RandomPort.class);
                final String value = annotation == null ? null : annotation.value();
                if (value != null && value.startsWith("http")) {
                    f.setAccessible(true);
                    ports.put(value, f);
                }
            }
            type = type.getSuperclass();
        }
    }

    if (ports.containsKey("http")) {
        configuration.randomHttpPort();
    }

    // at least after LifecycleTasks to inherit from potential states (system properties to get a port etc...)
    final Configurers configurers = appClass.getAnnotation(Configurers.class);
    if (configurers != null) {
        for (final Class<? extends Configurer> type : configurers.value()) {
            type.newInstance().configure(configuration);
        }
    }

    final Classes classes = appClass.getAnnotation(Classes.class);
    String context = classes != null ? classes.context() : "";
    context = !context.isEmpty() && context.startsWith("/") ? context.substring(1) : context;

    Archive archive = null;
    if (classes != null && classes.value().length > 0) {
        archive = new ClassesArchive(classes.value());
    }

    final Jars jars = appClass.getAnnotation(Jars.class);
    final List<URL> urls;
    if (jars != null) {
        final Collection<File> files = ApplicationComposers.findFiles(jars);
        urls = new ArrayList<>(files.size());
        for (final File f : files) {
            urls.add(f.toURI().toURL());
        }
    } else {
        urls = null;
    }

    final WebResource resources = appClass.getAnnotation(WebResource.class);
    if (resources != null && resources.value().length > 1) {
        throw new IllegalArgumentException("Only one docBase is supported for now using @WebResource");
    }

    String webResource = null;
    if (resources != null && resources.value().length > 0) {
        webResource = resources.value()[0];
    } else {
        final File webapp = new File("src/main/webapp");
        if (webapp.isDirectory()) {
            webResource = "src/main/webapp";
        }
    }

    if (config != null) { // override other config from annotations
        configuration.loadFromProperties(config);
    }

    final Container container = new Container(configuration);
    SystemInstance.get().setComponent(TomEEEmbeddedArgs.class, new TomEEEmbeddedArgs(args, null));
    SystemInstance.get().setComponent(LifecycleTaskAccessor.class, new LifecycleTaskAccessor(lifecycleTasks));
    container.deploy(new Container.DeploymentRequest(context,
            // call ClasspathSearcher that lazily since container needs to be started to not preload logging
            urls == null
                    ? new DeploymentsResolver.ClasspathSearcher()
                            .loadUrls(Thread.currentThread().getContextClassLoader()).getUrls()
                    : urls,
            webResource != null ? new File(webResource) : null, true, null, archive));

    for (final Map.Entry<String, Field> f : ports.entrySet()) {
        switch (f.getKey()) {
        case "http":
            setPortField(f.getKey(), f.getValue(), configuration, context, app);
            break;
        case "https":
            break;
        default:
            throw new IllegalArgumentException("port " + f.getKey() + " not yet supported");
        }
    }

    SystemInstance.get().addObserver(app);
    composerInject(app);

    final AnnotationFinder appFinder = new AnnotationFinder(new ClassesArchive(appClass));
    for (final Method mtd : appFinder.findAnnotatedMethods(PostConstruct.class)) {
        if (mtd.getParameterTypes().length == 0) {
            if (!mtd.isAccessible()) {
                mtd.setAccessible(true);
            }
            mtd.invoke(app);
        }
    }

    hook = new Thread() {
        @Override
        public void run() { // ensure to log errors but not fail there
            for (final Method mtd : appFinder.findAnnotatedMethods(PreDestroy.class)) {
                if (mtd.getParameterTypes().length == 0) {
                    if (!mtd.isAccessible()) {
                        mtd.setAccessible(true);
                    }
                    try {
                        mtd.invoke(app);
                    } catch (final IllegalAccessException e) {
                        throw new IllegalStateException(e);
                    } catch (final InvocationTargetException e) {
                        throw new IllegalStateException(e.getCause());
                    }
                }
            }

            try {
                container.close();
            } catch (final Exception e) {
                e.printStackTrace();
            }
            for (final Closeable c : postTasks) {
                try {
                    c.close();
                } catch (final IOException e) {
                    e.printStackTrace();
                }
            }
            postTasks.clear();
            app = null;
            try {
                SHUTDOWN_TASKS.remove(this);
            } catch (final Exception e) {
                // no-op: that's ok at that moment if not called manually
            }
        }
    };
    SHUTDOWN_TASKS.put(hook, hook);
}

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

/**
 * Use reflection to call the appropriate <code>visit</code> method
 * on the provided visitor, passing in the specified argument.
 * @param visitor the visitor encapsulating the logic to process the argument
 * @param argument the argument to dispatch
 * @throws IllegalArgumentException if the visitor parameter is null
 *///from   w w  w  .j a  va  2s  .  c  om
public Object invokeVisit(Object visitor, Object argument) {
    Assert.notNull(visitor, "The visitor to visit is required");
    // Perform call back on the visitor through reflection.
    Method method = getMethod(visitor.getClass(), argument);
    if (method == null) {
        if (logger.isWarnEnabled()) {
            logger.warn("No method found by reflection for visitor class [" + visitor.getClass().getName()
                    + "] and argument of type [" + (argument != null ? argument.getClass().getName() : "")
                    + "]");
        }
        return null;
    }
    try {
        Object[] args = null;
        if (argument != null) {
            args = new Object[] { argument };
        }
        if (!Modifier.isPublic(method.getModifiers()) && !method.isAccessible()) {
            method.setAccessible(true);
        }
        return method.invoke(visitor, args);

    } catch (Exception ex) {
        ReflectionUtils.handleReflectionException(ex);
        throw new IllegalStateException("Should never get here");
    }
}

From source file:com.alibaba.dubbo.config.spring.ServiceBean.java

public void setApplicationContext(ApplicationContext applicationContext) {
    this.applicationContext = applicationContext;
    SpringExtensionFactory.addApplicationContext(applicationContext);
    if (applicationContext != null) {
        SPRING_CONTEXT = applicationContext;
        try {/*www .j a va  2  s .co  m*/
            Method method = applicationContext.getClass().getMethod("addApplicationListener",
                    new Class<?>[] { ApplicationListener.class }); // Spring2.0.1
            method.invoke(applicationContext, new Object[] { this });
            supportedApplicationListener = true;
        } catch (Throwable t) {
            if (applicationContext instanceof AbstractApplicationContext) {
                try {
                    Method method = AbstractApplicationContext.class.getDeclaredMethod("addListener",
                            new Class<?>[] { ApplicationListener.class }); // Spring2.0.1
                    if (!method.isAccessible()) {
                        method.setAccessible(true);
                    }
                    method.invoke(applicationContext, new Object[] { this });
                    supportedApplicationListener = true;
                } catch (Throwable t2) {
                }
            }
        }
    }
}

From source file:com.baidu.jprotobuf.mojo.PreCompileMojo.java

/**
 * Execute goal.// ww w.ja va 2s.  c  o m
 * 
 * @throws MojoExecutionException execution of the main class or one of the threads it generated failed.
 * @throws MojoFailureException something bad happened...
 */
public void execute() throws MojoExecutionException, MojoFailureException {
    if (isSkip()) {
        getLog().info("skipping execute as per configuraion");
        return;
    }
    if (killAfter != -1) {
        getLog().warn("Warning: killAfter is now deprecated. Do you need it ? Please comment on MEXEC-6.");
    }

    arguments = new String[] { outputParentDirectory.getAbsolutePath(), outputDirectory.getAbsolutePath(),
            filterClassPackage };

    if (getLog().isDebugEnabled()) {
        StringBuffer msg = new StringBuffer("Invoking : ");
        msg.append(mainClass);
        msg.append(".main(");
        for (int i = 0; i < arguments.length; i++) {
            if (i > 0) {
                msg.append(", ");
            }
            msg.append(arguments[i]);
        }
        msg.append(")");
        getLog().debug(msg);
    }

    final Log log = getLog();
    IsolatedThreadGroup threadGroup = new IsolatedThreadGroup(mainClass /* name */);
    Thread bootstrapThread = new Thread(threadGroup, new Runnable() {
        public void run() {
            long current = System.currentTimeMillis();
            try {

                Method main = Thread.currentThread().getContextClassLoader().loadClass(mainClass)
                        .getMethod("main", new Class[] { String[].class });
                if (!main.isAccessible()) {
                    getLog().debug("Setting accessibility to true in order to invoke main().");
                    main.setAccessible(true);
                }
                if (!Modifier.isStatic(main.getModifiers())) {
                    throw new MojoExecutionException(
                            "Can't call main(String[])-method because it is not static.");
                }
                main.invoke(null, new Object[] { arguments });
            } catch (NoSuchMethodException e) { // just pass it on
                Thread.currentThread().getThreadGroup().uncaughtException(Thread.currentThread(), new Exception(
                        "The specified mainClass doesn't contain a main method with appropriate signature.",
                        e));
            } catch (Exception e) { // just pass it on
                Thread.currentThread().getThreadGroup().uncaughtException(Thread.currentThread(), e);
            } finally {
                log.info("JProtobuf pre compile done time took: " + (System.currentTimeMillis() - current)
                        + "ms");
            }
        }
    }, mainClass + ".main()");
    bootstrapThread.setContextClassLoader(getClassLoader());
    setSystemProperties();

    bootstrapThread.start();
    joinNonDaemonThreads(threadGroup);
    // It's plausible that spontaneously a non-daemon thread might be created as we try and shut down,
    // but it's too late since the termination condition (only daemon threads) has been triggered.
    if (keepAlive) {
        getLog().warn(
                "Warning: keepAlive is now deprecated and obsolete. Do you need it? Please comment on MEXEC-6.");
        waitFor(0);
    }

    if (cleanupDaemonThreads) {

        terminateThreads(threadGroup);

        try {
            threadGroup.destroy();
        } catch (IllegalThreadStateException e) {
            getLog().warn("Couldn't destroy threadgroup " + threadGroup, e);
        }
    }

    if (originalSystemProperties != null) {
        System.setProperties(originalSystemProperties);
    }

    synchronized (threadGroup) {
        if (threadGroup.uncaughtException != null) {
            throw new MojoExecutionException("An exception occured while executing the Java class. "
                    + threadGroup.uncaughtException.getMessage(), threadGroup.uncaughtException);
        }
    }

    registerSourceRoots();
}

From source file:org.cloudifysource.dsl.internal.BaseDslScript.java

private void validateObject(final Object obj) throws DSLValidationException {

    final Method[] methods = obj.getClass().getDeclaredMethods();
    for (final Method method : methods) {
        if (method.getAnnotation(DSLValidation.class) != null) {
            final boolean accessible = method.isAccessible();
            try {
                @SuppressWarnings("unchecked")
                final Map<Object, Object> currentVars = this.getBinding().getVariables();
                final DSLValidationContext validationContext = new DSLValidationContext();
                validationContext.setFilePath((String) currentVars.get(DSLUtils.DSL_FILE_PATH_PROPERTY_NAME));
                method.setAccessible(true);
                method.invoke(obj, validationContext);

            } catch (final InvocationTargetException e) {
                throw new DSLValidationException(e.getTargetException().getMessage(), e.getTargetException());
            } catch (final Exception e) {
                throw new DSLValidationException("Failed to execute DSL validation: " + e.getMessage(), e);

            } finally {
                method.setAccessible(accessible);
            }/*www  . ja  v  a2 s  .  c  o  m*/
        }
    }

}

From source file:com.impetus.kundera.proxy.cglib.CglibLazyInitializer.java

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (constructed) {

        String methodName = method.getName();
        int params = args.length;

        if (params == 0) {

            if (isUninitialized() && method.equals(getIdentifierMethod)) {
                return getIdentifier();
            }//  w ww .j  a  v a2  s . c o m

            else if ("getKunderaLazyInitializer".equals(methodName)) {
                return this;
            }

        }

        Object target = getImplementation();
        try {
            final Object returnValue;
            if (method.isAccessible()) {
                if (!method.getDeclaringClass().isInstance(target)) {
                    throw new ClassCastException(target.getClass().getName());
                }
                returnValue = method.invoke(target, args);
            } else {
                if (!method.isAccessible()) {
                    method.setAccessible(true);
                }
                returnValue = method.invoke(target, args);
            }
            return returnValue == target ? proxy : returnValue;
        } catch (InvocationTargetException ite) {
            throw ite.getTargetException();
        }
    } else {
        // while constructor is running
        throw new LazyInitializationException("unexpected case hit, method=" + method.getName());
    }

}