Java Code Examples for java.lang.reflect.Modifier.isPublic()

The following are Jave code examples for showing how to use isPublic() of the java.lang.reflect.Modifier class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: OpenJSharp   File: ConstructorFinder.java   Source Code and License Vote up 6 votes
/**
 * Finds public constructor
 * that is declared in public class.
 *
 * @param type  the class that can have constructor
 * @param args  parameter types that is used to find constructor
 * @return object that represents found constructor
 * @throws NoSuchMethodException if constructor could not be found
 *                               or some constructors are found
 */
public static Constructor<?> findConstructor(Class<?> type, Class<?>...args) throws NoSuchMethodException {
    if (type.isPrimitive()) {
        throw new NoSuchMethodException("Primitive wrapper does not contain constructors");
    }
    if (type.isInterface()) {
        throw new NoSuchMethodException("Interface does not contain constructors");
    }
    if (Modifier.isAbstract(type.getModifiers())) {
        throw new NoSuchMethodException("Abstract class cannot be instantiated");
    }
    if (!Modifier.isPublic(type.getModifiers()) || !isPackageAccessible(type)) {
        throw new NoSuchMethodException("Class is not accessible");
    }
    PrimitiveWrapperMap.replacePrimitivesWithWrappers(args);
    Signature signature = new Signature(type, args);

    try {
        return CACHE.get(signature);
    }
    catch (SignatureException exception) {
        throw exception.toNoSuchMethodException("Constructor is not found");
    }
}
 
Example 2
Project: GitHub   File: TypeUtils.java   Source Code and License Vote up 6 votes
public static Class<?> getCollectionItemClass(Type fieldType){
    if(fieldType instanceof ParameterizedType){
        Class<?> itemClass;
        Type actualTypeArgument = ((ParameterizedType) fieldType).getActualTypeArguments()[0];
        if(actualTypeArgument instanceof WildcardType){
            WildcardType wildcardType = (WildcardType) actualTypeArgument;
            Type[] upperBounds = wildcardType.getUpperBounds();
            if(upperBounds.length == 1){
                actualTypeArgument = upperBounds[0];
            }
        }
        if(actualTypeArgument instanceof Class){
            itemClass = (Class<?>) actualTypeArgument;
            if(!Modifier.isPublic(itemClass.getModifiers())){
                throw new JSONException("can not create ASMParser");
            }
        } else{
            throw new JSONException("can not create ASMParser");
        }
        return itemClass;
    }
    return Object.class;
}
 
Example 3
Project: jdk8u-jdk   File: JMX.java   Source Code and License Vote up 6 votes
/**
 * <p>Test whether an interface is an MXBean interface.
 * An interface is an MXBean interface if it is public,
 * annotated {@link MXBean &#64;MXBean} or {@code @MXBean(true)}
 * or if it does not have an {@code @MXBean} annotation
 * and its name ends with "{@code MXBean}".</p>
 *
 * @param interfaceClass The candidate interface.
 *
 * @return true if {@code interfaceClass} is a
 * {@link javax.management.MXBean compliant MXBean interface}
 *
 * @throws NullPointerException if {@code interfaceClass} is null.
 */
public static boolean isMXBeanInterface(Class<?> interfaceClass) {
    if (!interfaceClass.isInterface())
        return false;
    if (!Modifier.isPublic(interfaceClass.getModifiers()) &&
        !Introspector.ALLOW_NONPUBLIC_MBEAN) {
        return false;
    }
    MXBean a = interfaceClass.getAnnotation(MXBean.class);
    if (a != null)
        return a.value();
    return interfaceClass.getName().endsWith("MXBean");
    // We don't bother excluding the case where the name is
    // exactly the string "MXBean" since that would mean there
    // was no package name, which is pretty unlikely in practice.
}
 
Example 4
Project: MaxSim   File: JSJavaScriptEngine.java   Source Code and License Vote up 6 votes
protected JSJavaScriptEngine(boolean debug) {
    this.debug = debug;
  ScriptEngineManager manager = new ScriptEngineManager();
  engine = manager.getEngineByName("javascript");
  if (engine == null) {
    throw new RuntimeException("can't load JavaScript engine");
  }
  Method[] methods = getClass().getMethods();
  for (int i = 0; i < methods.length; i++) {
    Method m = methods[i];
    if (! Modifier.isPublic(m.getModifiers())) {
      continue;
    }
    Class[] argTypes = m.getParameterTypes();
    if (argTypes.length == 1 &&
        argTypes[0] == Object[].class) {
      putFunction(this, m);
    }
  }
}
 
Example 5
Project: Cubes_2   File: LuaConversion.java   Source Code and License Vote up 6 votes
public static LuaValue complexToLua(Object o) {
	try {
		Class<?> c = o.getClass();
		Field[] fields = c.getFields();
		LuaTable table = new LuaTable();
		for (Field field : fields) {
			if (!(Modifier.isPublic(field.getModifiers()) || field.isAnnotationPresent(LuaInclude.class))
					|| field.isAnnotationPresent(LuaExclude.class))
				continue;
			String name = field.getName();
			Class<?> type = field.getType();
			Object instance = field.get(o);
			LuaValue l = convertToLua(instance);
			table.set(name, l);
		}
		return table;
	} catch (Exception e) {
		Log.warning(e);
	}
	return NIL;
}
 
Example 6
Project: businessworks   File: InjectionPoint.java   Source Code and License Vote up 5 votes
/**
 * Returns true if a overrides b. Assumes signatures of a and b are the same and a's declaring
 * class is a subclass of b's declaring class.
 */
private static boolean overrides(Method a, Method b) {
  // See JLS section 8.4.8.1
  int modifiers = b.getModifiers();
  if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers)) {
    return true;
  }
  if (Modifier.isPrivate(modifiers)) {
    return false;
  }
  // b must be package-private
  return a.getDeclaringClass().getPackage().equals(b.getDeclaringClass().getPackage());
}
 
Example 7
Project: azeroth   File: ReflectUtils.java   Source Code and License Vote up 5 votes
public static boolean isBeanPropertyReadMethod(Method method) {
    return method != null
            && Modifier.isPublic(method.getModifiers())
            && !Modifier.isStatic(method.getModifiers())
            && method.getReturnType() != void.class
            && method.getDeclaringClass() != Object.class
            && method.getParameterTypes().length == 0
            && ((method.getName().startsWith("get") && method.getName()
            .length() > 3) || (method.getName().startsWith("is") && method
            .getName().length() > 2));
}
 
Example 8
Project: parabuild-ci   File: CloneableBean.java   Source Code and License Vote up 5 votes
private Object doClone(Object value) throws Exception {
    if (value!=null) {
        Class vClass = value.getClass();
        if (vClass.isArray()) {
            value = cloneArray(value);
        }
        else
        if (value instanceof Collection) {
            value = cloneCollection((Collection)value);
        }
        else
        if (value instanceof Map) {
            value = cloneMap((Map)value);
        }
        else
        if (isBasicType(vClass)) {
            // NOTHING SPECIAL TO DO HERE, THEY ARE INMUTABLE
        }
        else
        if (value instanceof Cloneable) {
            Method cloneMethod = vClass.getMethod("clone",NO_PARAMS_DEF);
            if (Modifier.isPublic(cloneMethod.getModifiers())) {
               value = cloneMethod.invoke(value,NO_PARAMS);
            }
            else {
                throw new CloneNotSupportedException("Cannot clone a "+value.getClass()+" object, clone() is not public");
            }
        }
        else {
            throw new CloneNotSupportedException("Cannot clone a "+vClass.getName()+" object");
        }
    }
    return value;
}
 
Example 9
Project: javaide   File: ClassDescription.java   Source Code and License Vote up 5 votes
public ClassDescription(Class value) {
    this.simpleName = value.getSimpleName();
    this.name = value.getSimpleName();
    this.className = value.getName();
    if (value.getSuperclass() != null) {
        this.extend = value.getSuperclass().getName();
    }
    this.packageName = JavaUtil.getPackageName(className);
    this.lastUsed = 0;


    constructors = new ArrayList<>();
    fields = new ArrayList<>();
    methods = new ArrayList<>();

    for (Constructor constructor : value.getConstructors()) {
        if (Modifier.isPublic(constructor.getModifiers())) {
            addConstructor(new ConstructorDescription(constructor));
        }
    }
    for (Field field : value.getDeclaredFields()) {
        if (Modifier.isPublic(field.getModifiers())) {
            if (!field.getName().equals(field.getDeclaringClass().getName())) {
                addField(new FieldDescription(field));
            }
        }
    }
    for (Method method : value.getMethods()) {
        if (Modifier.isPublic(method.getModifiers())) {
            addMethod(new MethodDescription(method));
        }
    }
}
 
Example 10
Project: boohee_v5.6   File: ASMDeserializerFactory.java   Source Code and License Vote up 5 votes
private Class<?> getCollectionItemClass(Type fieldType) {
    if (!(fieldType instanceof ParameterizedType)) {
        return Object.class;
    }
    Type actualTypeArgument = ((ParameterizedType) fieldType).getActualTypeArguments()[0];
    if (actualTypeArgument instanceof Class) {
        Class<?> cls = (Class) actualTypeArgument;
        if (Modifier.isPublic(cls.getModifiers())) {
            return cls;
        }
        throw new ASMException("can not create ASMParser");
    }
    throw new ASMException("can not create ASMParser");
}
 
Example 11
Project: monarch   File: ResultsCollectionWrapper.java   Source Code and License Vote up 5 votes
private void validateConstraint(ObjectType constraint) {
  if (constraint == null)
    throw new IllegalArgumentException(
        LocalizedStrings.ResultsCollectionWrapper_CONSTRAINT_CANNOT_BE_NULL.toLocalizedString());
  // must be public
  if (!Modifier.isPublic(constraint.resolveClass().getModifiers()))
    throw new IllegalArgumentException(
        LocalizedStrings.ResultsCollectionWrapper_CONSTRAINT_CLASS_MUST_BE_PUBLIC
            .toLocalizedString());
}
 
Example 12
Project: DroidPlugin   File: MethodUtils.java   Source Code and License Vote up 5 votes
private static Method getAccessibleMethodFromInterfaceNest(Class<?> cls,
                                                           final String methodName, final Class<?>... parameterTypes) {
    // Search up the superclass chain
    for (; cls != null; cls = cls.getSuperclass()) {

        // Check the implemented interfaces of the parent class
        final Class<?>[] interfaces = cls.getInterfaces();
        for (int i = 0; i < interfaces.length; i++) {
            // Is this interface public?
            if (!Modifier.isPublic(interfaces[i].getModifiers())) {
                continue;
            }
            // Does the method exist on this interface?
            try {
                return interfaces[i].getDeclaredMethod(methodName,
                        parameterTypes);
            } catch (final NoSuchMethodException e) { // NOPMD
                /*
                 * Swallow, if no method is found after the loop then this
                 * method returns null.
                 */
            }
            // Recursively check our parent interfaces
            Method method = getAccessibleMethodFromInterfaceNest(interfaces[i],
                    methodName, parameterTypes);
            if (method != null) {
                return method;
            }
        }
    }
    return null;
}
 
Example 13
Project: DroidPlugin   File: MemberUtils.java   Source Code and License Vote up 5 votes
static boolean setAccessibleWorkaround(final AccessibleObject o) {
    if (o == null || o.isAccessible()) {
        return false;
    }
    final Member m = (Member) o;
    if (!o.isAccessible() && Modifier.isPublic(m.getModifiers()) && isPackageAccess(m.getDeclaringClass().getModifiers())) {
        try {
            o.setAccessible(true);
            return true;
        } catch (final SecurityException e) { // NOPMD
            // ignore in favor of subsequent IllegalAccessException
        }
    }
    return false;
}
 
Example 14
Project: boohee_v5.6   File: ASMDeserializerFactory.java   Source Code and License Vote up 5 votes
private void _createInstance(Context context, MethodVisitor mw) {
    if (Modifier.isPublic(context.getBeanInfo().getDefaultConstructor().getModifiers())) {
        mw.visitTypeInsn(187, ASMUtils.getType(context.getClazz()));
        mw.visitInsn(89);
        mw.visitMethodInsn(183, ASMUtils.getType(context.getClazz()), "<init>", "()V");
        mw.visitVarInsn(58, context.var("instance"));
        return;
    }
    mw.visitVarInsn(25, 0);
    mw.visitVarInsn(25, 1);
    mw.visitMethodInsn(183, "com/alibaba/fastjson/parser/deserializer/ASMJavaBeanDeserializer", "createInstance", "(Lcom/alibaba/fastjson/parser/DefaultJSONParser;)Ljava/lang/Object;");
    mw.visitTypeInsn(192, ASMUtils.getType(context.getClazz()));
    mw.visitVarInsn(58, context.var("instance"));
}
 
Example 15
Project: OpenDiabetes   File: JDBCParameterMetaData.java   Source Code and License Vote up 4 votes
/**
 * Provides the implementation of the toString() method. <p>
 *
 * @return a String representation of this object
 * @throws Exception if a reflection error occurs
 */
private String toStringImpl() throws Exception {

    StringBuffer sb;
    Method[]     methods;
    Method       method;
    int          count;

    sb = new StringBuffer();

    sb.append(super.toString());

    count = getParameterCount();

    if (count == 0) {
        sb.append("[parameterCount=0]");

        return sb.toString();
    }
    methods = getClass().getDeclaredMethods();

    sb.append('[');

    int len = methods.length;

    for (int i = 0; i < count; i++) {
        sb.append('\n');
        sb.append("    parameter_");
        sb.append(i + 1);
        sb.append('=');
        sb.append('[');

        for (int j = 0; j < len; j++) {
            method = methods[j];

            if (!Modifier.isPublic(method.getModifiers())) {
                continue;
            }

            if (method.getParameterTypes().length != 1) {
                continue;
            }
            sb.append(method.getName());
            sb.append('=');
            sb.append(method.invoke(this,
                                    new Object[] { Integer.valueOf(i + 1) }));

            if (j + 1 < len) {
                sb.append(',');
                sb.append(' ');
            }
        }
        sb.append(']');

        if (i + 1 < count) {
            sb.append(',');
            sb.append(' ');
        }
    }
    sb.append('\n');
    sb.append(']');

    return sb.toString();
}
 
Example 16
Project: parabuild-ci   File: ObjectConverter.java   Source Code and License Vote up 4 votes
public Map getPropertyMapFromClass(Class type, boolean readRequired, boolean writeRequired)
{
    Map allFields = new HashMap();

    while (type != Object.class)
    {
        Field[] fields = type.getDeclaredFields();

        fieldLoop:
        for (int i = 0; i < fields.length; i++)
        {
            Field field = fields[i];
            String name = field.getName();

            // We don't marshall getClass()
            if ("class".equals(name))
            {
                continue fieldLoop;
            }

            // Access rules mean we might not want to do this one
            if (!isAllowedByIncludeExcludeRules(name))
            {
                continue fieldLoop;
            }

            if (!Modifier.isPublic(field.getModifiers()))
            {
                if (force)
                {
                    field.setAccessible(true);
                }
                else
                {
                    continue fieldLoop;
                }
            }

            allFields.put(name, new FieldProperty(field));
        }

        type = type.getSuperclass();
    }

    return allFields;
}
 
Example 17
Project: lazycat   File: PojoMethodMapping.java   Source Code and License Vote up 4 votes
private void checkPublic(Method m) throws DeploymentException {
	if (!Modifier.isPublic(m.getModifiers())) {
		throw new DeploymentException(sm.getString("pojoMethodMapping.methodNotPublic", m.getName()));
	}
}
 
Example 18
Project: openrouteservice   File: JSONObject.java   Source Code and License Vote up 4 votes
private void populateMap(Object bean) {
        Class<?> klass = bean.getClass();

// If klass is a System class then set includeSuperClass to false.

        boolean includeSuperClass = klass.getClassLoader() != null;

        Method[] methods = includeSuperClass ? klass.getMethods() : klass
                .getDeclaredMethods();
        for (int i = 0; i < methods.length; i += 1) {
            try {
                Method method = methods[i];
                if (Modifier.isPublic(method.getModifiers())) {
                    String name = method.getName();
                    String key = "";
                    if (name.startsWith("get")) {
                        if ("getClass".equals(name)
                                || "getDeclaringClass".equals(name)) {
                            key = "";
                        } else {
                            key = name.substring(3);
                        }
                    } else if (name.startsWith("is")) {
                        key = name.substring(2);
                    }
                    if (key.length() > 0
                            && Character.isUpperCase(key.charAt(0))
                            && method.getParameterTypes().length == 0) {
                        if (key.length() == 1) {
                            key = key.toLowerCase(Locale.ROOT);
                        } else if (!Character.isUpperCase(key.charAt(1))) {
                            key = key.substring(0, 1).toLowerCase(Locale.ROOT)
                                    + key.substring(1);
                        }

                        Object result = method.invoke(bean, (Object[]) null);
                        if (result != null) {
                            this.map.put(key, wrap(result));
                        }
                    }
                }
            } catch (Exception ignore) {
            }
        }
    }
 
Example 19
Project: openjdk-jdk10   File: Context.java   Source Code and License Vote up 2 votes
/**
 * Checks that the given Class is public and it can be accessed from no permissions context.
 *
 * @param clazz Class object to check
 * @return true if Class is accessible, false otherwise
 */
public static boolean isAccessibleClass(final Class<?> clazz) {
    return Modifier.isPublic(clazz.getModifiers()) && Context.isAccessiblePackage(clazz);
}
 
Example 20
Project: AndHook   File: MemberUtils.java   Source Code and License Vote up 2 votes
/**
 * Returns whether a Member is accessible.
 *
 * @param m Member to check
 * @return true if <code>m</code> is accessible
 */
static boolean isAccessible(Member m) {
    return m != null && Modifier.isPublic(m.getModifiers()) && !m.isSynthetic();
}