Example usage for java.lang.reflect Modifier isPublic

List of usage examples for java.lang.reflect Modifier isPublic

Introduction

In this page you can find the example usage for java.lang.reflect Modifier isPublic.

Prototype

public static boolean isPublic(int mod) 

Source Link

Document

Return true if the integer argument includes the public modifier, false otherwise.

Usage

From source file:com.nonninz.robomodel.RoboModel.java

List<Field> getSavedFields() { //TODO: cache results
    final List<Field> savedFields = new ArrayList<Field>();

    final Field[] declaredFields = getClass().getDeclaredFields();
    boolean saved;
    for (final Field field : declaredFields) {

        saved = false;//from   www.  j a v  a 2s.c o m
        saved = saved || field.isAnnotationPresent(Save.class); // If @Save is present, save it
        saved = saved || Modifier.isPublic(field.getModifiers()); // If it is public, save it
        saved = saved && !Modifier.isStatic(field.getModifiers()); // If it is static, don't save it
        saved = saved && !field.isAnnotationPresent(Exclude.class); // If @Exclude, don't save it

        if (saved) {
            savedFields.add(field);
        }
    }

    return savedFields;
}

From source file:net.sf.cocmvc.ConventionalHandlerMapping.java

private boolean isAction(Method method) {
    String name = method.getName();
    return Modifier.isPublic(method.getModifiers())
            && !(name.matches("^(equals|hashCode|toString|clone|notify.*|wait|getClass)") // methods declared in Object
                    || name.matches("^(init|destroy)") // common lifecycle methods
                    || name.matches("^([sg]et(MetaClass|Property)|.*\\$.*|invokeMethod)") // methods of groovy object
                    || findAnnotation(method, NoMapping.class) != null);
}

From source file:Main.java

/**
 * Returns a clone of the specified object, if it can be cloned, otherwise
 * throws a CloneNotSupportedException.//from   w  ww  .j  av  a 2 s  . c o m
 * 
 * @param object
 *          the object to clone (<code>null</code> not permitted).
 * @return A clone of the specified object.
 * @throws CloneNotSupportedException
 *           if the object cannot be cloned.
 */
public static Object clone(final Object object) throws CloneNotSupportedException {
    if (object == null) {
        throw new IllegalArgumentException("Null 'object' argument.");
    }

    try {
        final Method method = object.getClass().getMethod("clone", (Class[]) null);
        if (Modifier.isPublic(method.getModifiers())) {
            return method.invoke(object, (Object[]) null);
        }
    } catch (NoSuchMethodException e) {
        System.out.println("Object without clone() method is impossible.");
    } catch (IllegalAccessException e) {
        System.out.println("Object.clone(): unable to call method.");
    } catch (InvocationTargetException e) {
        System.out.println("Object without clone() method is impossible.");
    }

    throw new CloneNotSupportedException("Failed to clone.");
}

From source file:tools.xor.util.ClassUtil.java

/**
 * Invoke the given method as a privileged action, if necessary.
 * @param target the object on which the method needs to be invoked
 * @param method to invoke//from   ww  w  .j av a2s  .c  o m
 * @param args to the method
 * @return result of the invocation
 * @throws InvocationTargetException while invoking the method
 * @throws IllegalAccessException when accessing the meta data
 */
//public static Object invokeMethodAsPrivileged(final Object target, final Method method, final Object[] args) 
public static Object invokeMethodAsPrivileged(final Object target, final Method method, final Object... args)
        throws InvocationTargetException, IllegalAccessException {
    if (Modifier.isPublic(method.getModifiers()))
        if (args == null)
            return method.invoke(target);
        else
            return method.invoke(target, args);
    return AccessController.doPrivileged(new PrivilegedAction<Object>() {
        public Object run() {
            method.setAccessible(true);
            Object result = null;
            try {
                if (args == null)
                    result = method.invoke(target);
                else
                    result = method.invoke(target, args);
            } catch (Exception e) {
                throw wrapRun(e);
            }
            return result;
        }
    });
}

From source file:ninja.eivind.hotsreplayuploader.ClientTest.java

@Test
public void testClientIsMainClass() throws Exception {
    String className = parse.select("project > properties > mainClass").text();

    LOG.info("Loading class " + className);
    Class<?> mainClass = Class.forName(className);

    Method main = mainClass.getDeclaredMethod("main", String[].class);
    int modifiers = main.getModifiers();

    Class<?> returnType = main.getReturnType();

    assertEquals("Client is mainClass", Client.class, mainClass);
    assertSame("Main method returns void", returnType, Void.TYPE);
    assertTrue("Main method is static", Modifier.isStatic(modifiers));
    assertTrue("Main method is public", Modifier.isPublic(modifiers));
}

From source file:org.braiden.fpm2.util.PropertyUtils.java

public static Map<String, Object> describe(Object bean)
        throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    Validate.notNull(bean);//from w  w  w  .j  a v a2s  . c om

    Map<String, Object> result = new HashMap<String, Object>();

    for (Method method : bean.getClass().getMethods()) {
        boolean isAccepted = Modifier.isPublic(method.getModifiers())
                && !Modifier.isStatic(method.getModifiers()) && method.getParameterTypes().length == 0
                && !METHOD_GET_CLASS.equals(method.getName());

        boolean isObjGetter = isAccepted && !Void.class.isAssignableFrom(method.getReturnType())
                && method.getName().startsWith(GETTER_PREFIX);
        boolean isBooleanGetter = isAccepted
                && (Boolean.class.isAssignableFrom(method.getReturnType())
                        || boolean.class.isAssignableFrom(method.getReturnType()))
                && method.getName().startsWith(GETTER_BOOLEAN_PREFIX);

        if (isObjGetter || isBooleanGetter) {
            String propName = StringUtils
                    .uncapitalize(isObjGetter ? method.getName().substring(GETTER_PREFIX.length())
                            : method.getName().substring(GETTER_BOOLEAN_PREFIX.length()));
            result.put(propName, method.invoke(bean));
        }
    }

    return result;
}

From source file:com.alibaba.dubbo.governance.web.common.module.screen.Restful.java

public void execute(Map<String, Object> context) throws Throwable {
    if (context.get(WebConstants.CURRENT_USER_KEY) != null) {
        User user = (User) context.get(WebConstants.CURRENT_USER_KEY);
        currentUser = user;//  w ww  .  j a  v a 2 s.c o m
        operator = user.getUsername();
        role = user.getRole();
        context.put(WebConstants.CURRENT_USER_KEY, user);
    }
    operatorAddress = (String) context.get("request.remoteHost");
    context.put("operator", operator);
    context.put("operatorAddress", operatorAddress);

    context.put("currentRegistry", currentRegistry);

    String httpMethod = (String) context.get("request.method");
    String method = (String) context.get("_method");
    String contextPath = (String) context.get("request.contextPath");
    context.put("rootContextPath", new RootContextPath(contextPath));

    // ?Method
    if (method == null || method.length() == 0) {
        String id = (String) context.get("id");
        if (id == null || id.length() == 0) {
            method = "index";
        } else {
            method = "show";
        }
    }
    if ("index".equals(method)) {
        if ("post".equalsIgnoreCase(httpMethod)) {
            method = "create";
        }
    } else if ("show".equals(method)) {
        if ("put".equalsIgnoreCase(httpMethod) || "post".equalsIgnoreCase(httpMethod)) { // ????PUTPOST
            method = "update";
        } else if ("delete".equalsIgnoreCase(httpMethod)) { // ????DELETE?
            method = "delete";
        }
    }
    context.put("_method", method);

    try {
        Method m = null;
        try {
            m = getClass().getMethod(method, new Class<?>[] { Map.class });
        } catch (NoSuchMethodException e) {
            for (Method mtd : getClass().getMethods()) {
                if (Modifier.isPublic(mtd.getModifiers()) && mtd.getName().equals(method)) {
                    m = mtd;
                    break;
                }
            }
            if (m == null) {
                throw e;
            }
        }
        if (m.getParameterTypes().length > 2) {
            throw new IllegalStateException("Unsupport restful method " + m);
        } else if (m.getParameterTypes().length == 2 && (m.getParameterTypes()[0].equals(Map.class)
                || !m.getParameterTypes()[1].equals(Map.class))) {
            throw new IllegalStateException("Unsupport restful method " + m);
        }
        Object r;
        if (m.getParameterTypes().length == 0) {
            r = m.invoke(this, new Object[0]);
        } else {
            Object value;
            Class<?> t = m.getParameterTypes()[0];
            if (Map.class.equals(t)) {
                value = context;
            } else if (isPrimitive(t)) {
                String id = (String) context.get("id");
                value = convertPrimitive(t, id);
            } else if (t.isArray() && isPrimitive(t.getComponentType())) {
                String id = (String) context.get("id");
                String[] ids = id == null ? new String[0] : id.split("[.+]+");
                value = Array.newInstance(t.getComponentType(), ids.length);
                for (int i = 0; i < ids.length; i++) {
                    Array.set(value, i, convertPrimitive(t.getComponentType(), ids[i]));
                }
            } else {
                value = t.newInstance();
                for (Method mtd : t.getMethods()) {
                    if (Modifier.isPublic(mtd.getModifiers()) && mtd.getName().startsWith("set")
                            && mtd.getParameterTypes().length == 1) {
                        String p = mtd.getName().substring(3, 4).toLowerCase() + mtd.getName().substring(4);
                        Object v = context.get(p);
                        if (v == null) {
                            if ("operator".equals(p)) {
                                v = operator;
                            } else if ("operatorAddress".equals(p)) {
                                v = (String) context.get("request.remoteHost");
                            }
                        }
                        if (v != null) {
                            try {
                                mtd.invoke(value, new Object[] { CompatibleTypeUtils.compatibleTypeConvert(v,
                                        mtd.getParameterTypes()[0]) });
                            } catch (Throwable e) {
                                logger.warn(e.getMessage(), e);
                            }
                        }
                    }
                }
            }
            if (m.getParameterTypes().length == 1) {
                r = m.invoke(this, new Object[] { value });
            } else {
                r = m.invoke(this, new Object[] { value, context });
            }
        }
        if (m.getReturnType() == boolean.class || m.getReturnType() == Boolean.class) {
            context.put("rundata.layout", "redirect");
            context.put("rundata.target", "redirect");
            context.put("success", r == null || ((Boolean) r).booleanValue());
            if (context.get("redirect") == null) {
                context.put("redirect", getDefaultRedirect(context, method));
            }
        } else if (m.getReturnType() == String.class) {
            String redirect = (String) r;
            if (redirect == null) {
                redirect = getDefaultRedirect(context, method);
            }

            if (context.get("chain") != null) {
                context.put("rundata.layout", "home");
                context.put("rundata.target", "home");
            } else {
                context.put("rundata.redirect", redirect);
            }
        } else {
            context.put("rundata.layout", method);
            context.put("rundata.target", context.get("rundata.target") + "/" + method);
        }
    } catch (Throwable e) {
        if (e instanceof InvocationTargetException) {
            throw ((InvocationTargetException) e).getTargetException();
        }
        //            if (e instanceof InvocationTargetException) {
        //                e = ((InvocationTargetException) e).getTargetException();
        //            }
        //            logger.warn(e.getMessage(), e);
        //            context.put("rundata.layout", "redirect");
        //            context.put("rundata.target", "redirect");
        //            context.put("success", false);
        //            context.put("exception", e);
        //            context.put("redirect", getDefaultRedirect(context, method));
    }
}

From source file:org.cruxframework.crux.core.rebind.dto.DataObjects.java

/**
 * @param dataClass/*from   ww w .  j a v a2  s .co  m*/
 * @return
 */
private static String[] extractIdentifiers(Class<?> dataClass) {
    Class<?> dtoClass = dataClass;

    List<String> ids = new ArrayList<String>();
    while (dtoClass.getSuperclass() != null) {
        Field[] fields = dtoClass.getDeclaredFields();

        for (Field field : fields) {
            if (field.getAnnotation(DataObjectIdentifier.class) != null) {
                if (Modifier.isPublic(field.getModifiers())) {
                    ids.add(field.getName());
                } else {
                    ids.add(ClassUtils.getGetterMethod(field.getName(), dtoClass) + "()");
                }
            }
        }
        dtoClass = dtoClass.getSuperclass();
    }
    return ids.toArray(new String[ids.size()]);
}

From source file:com.taobao.diamond.common.Constants.java

/** ?-D &gt; env &gt; diamond.properties  */
public static void init() {
    File diamondFile = new File(System.getProperty("user.home"), "diamond/ServerAddress");
    if (!diamondFile.exists()) {
        diamondFile.getParentFile().mkdirs();
        try (OutputStream out = new FileOutputStream(diamondFile)) {
            out.write("localhost".getBytes());
        } catch (IOException e) {
            throw new IllegalStateException(diamondFile.toString(), e);
        }/*from w  w  w. j  ava2 s. c  o  m*/
    }
    List<Field> fields = new ArrayList<>();
    for (Field field : Constants.class.getDeclaredFields()) {
        if (Modifier.isPublic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers())) {
            fields.add(field);
        }
    }

    Properties props = new Properties();
    {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        if (cl == null)
            cl = Constants.class.getClassLoader();
        try (InputStream in = cl.getResourceAsStream("diamond.properties")) {
            if (in != null)
                props.load(in);
        } catch (IOException e) {
            log.warn("load diamond.properties", e);
        }
    }
    props.putAll(System.getenv());
    props.putAll(System.getProperties());

    Map<String, Object> old = new HashMap<>();
    try {
        for (Field field : fields) {
            if (!props.containsKey(field.getName()))
                continue;
            old.put(field.getName(), field.get(Constants.class));

            String value = props.getProperty(field.getName());
            Class<?> clazz = field.getType();
            if (String.class.equals(clazz)) {
                field.set(Constraints.class, value);
            } else if (int.class.equals(clazz)) {
                if (value != null) {
                    field.set(Constraints.class, Integer.parseInt(value));
                }
            } else {
                throw new IllegalArgumentException(field + "  " + value + " ?");
            }
        }
    } catch (IllegalAccessException e) {
        throw new IllegalStateException(e);
    }

    setValue(old, "CONFIG_HTTP_URI_FILE", "HTTP_URI_FILE");
    setValue(old, "HTTP_URI_LOGIN", "HTTP_URI_FILE");
    setValue(old, "DAILY_DOMAINNAME", "DEFAULT_DOMAINNAME");
}