List of usage examples for java.lang.reflect Modifier isPublic
public static boolean isPublic(int mod)
From source file:com.googlecode.ehcache.annotations.impl.CacheAttributeSourceImpl.java
private MethodAttribute computeMethodAttribute(Method method, Class<?> targetClass) { // Don't allow no-public methods as required. if (this.allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) { return null; }/*from w w w.j a v a2s . co m*/ // The method may be on an interface, but we need attributes from the target class. // If the target class is null, the method will be unchanged. Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass); // If we are dealing with method with generic parameters, find the original method. specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod); // First try is the method in the target class. MethodAttribute att = this.findMethodAttribute(specificMethod); if (att != null) { return att; } if (specificMethod != method) { // Fallback is to look at the original method. att = this.findMethodAttribute(method); if (att != null) { return att; } } return null; }
From source file:org.eclipse.skalli.services.persistence.EntityManagerServiceBase.java
static Set<String> getPublicStaticFinalFieldValues(Class<?> clazz) { Set<String> properties = new HashSet<String>(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (field.getType().isAssignableFrom(String.class)) { int mod = field.getModifiers(); if (Modifier.isPublic(mod) && Modifier.isStatic(mod) && Modifier.isFinal(mod)) { try { String propertyValue = field.get(null).toString(); if (StringUtils.isNotBlank(propertyValue)) { properties.add(propertyValue); }// www . j av a 2 s .c o m } catch (Exception e) { LOG.error("Failed to read public static final fields of class " + clazz, e); } } } } return properties; }
From source file:com.px100systems.util.serialization.SerializationDefinition.java
private SerializationDefinition(Class<?> cls) { definitions.put(cls, this); if (cls.getName().startsWith("java")) throw new RuntimeException("System classes are not supported: " + cls.getSimpleName()); try {/*from w w w .j a va2 s . com*/ constructor = cls.getConstructor(); } catch (NoSuchMethodException e) { throw new RuntimeException("Missing no-arg constructor: " + cls.getSimpleName()); } serializingSetter = ReflectionUtils.findMethod(cls, "setSerializing", boolean.class); for (Class<?> c = cls; c != null && !c.equals(Object.class); c = c.getSuperclass()) { for (Field field : c.getDeclaredFields()) { if (Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) continue; FieldDefinition fd = new FieldDefinition(); fd.name = field.getName(); fd.type = field.getType(); if (fd.type.isPrimitive()) throw new RuntimeException("Primitives are not supported: " + fd.type.getSimpleName()); Calculated calc = field.getAnnotation(Calculated.class); if (!fd.type.equals(Integer.class) && !fd.type.equals(Long.class) && !fd.type.equals(Double.class) && !fd.type.equals(Boolean.class) && !fd.type.equals(Date.class) && !fd.type.equals(String.class)) if (fd.type.equals(List.class) || fd.type.equals(Set.class)) { SerializedCollection sc = field.getAnnotation(SerializedCollection.class); if (sc == null) throw new RuntimeException( cls.getSimpleName() + "." + fd.name + " is missing @SerializedCollection"); if (calc != null) throw new RuntimeException(cls.getSimpleName() + "." + fd.name + " cannot have a calculator because it is a collection"); fd.collectionType = sc.type(); fd.primitive = fd.collectionType.equals(Integer.class) || fd.collectionType.equals(Long.class) || fd.collectionType.equals(Double.class) || fd.collectionType.equals(Boolean.class) || fd.collectionType.equals(Date.class) || fd.collectionType.equals(String.class); if (!fd.primitive) { if (cls.getName().startsWith("java")) throw new RuntimeException(cls.getSimpleName() + "." + fd.name + ": system collection types are not supported: " + fd.collectionType.getSimpleName()); if (!definitions.containsKey(fd.collectionType)) new SerializationDefinition(fd.collectionType); } } else { if (cls.getName().startsWith("java")) throw new RuntimeException( "System classes are not supported: " + fd.type.getSimpleName()); if (!definitions.containsKey(fd.type)) new SerializationDefinition(fd.type); } else fd.primitive = true; try { fd.accessor = c.getMethod(PropertyAccessor.methodName("get", fd.name)); } catch (NoSuchMethodException e) { throw new RuntimeException(cls.getSimpleName() + "." + fd.name + " is missing getter"); } try { fd.mutator = c.getMethod(PropertyAccessor.methodName("set", fd.name), fd.type); } catch (NoSuchMethodException e) { throw new RuntimeException(cls.getSimpleName() + "." + fd.name + " is missing setter"); } if (calc != null) fd.calculator = new SpelExpressionParser().parseExpression(calc.value()); fields.add(fd); } for (Method method : c.getDeclaredMethods()) if (Modifier.isPublic(method.getModifiers()) && !Modifier.isStatic(method.getModifiers()) && method.getName().startsWith("get") && method.isAnnotationPresent(SerializedGetter.class)) { FieldDefinition fd = new FieldDefinition(); fd.name = method.getName().substring(3); fd.name = fd.name.substring(0, 1).toLowerCase() + fd.name.substring(1); fd.type = method.getReturnType(); fd.primitive = fd.type != null && (fd.type.equals(Integer.class) || fd.type.equals(Long.class) || fd.type.equals(Double.class) || fd.type.equals(Boolean.class) || fd.type.equals(Date.class) || fd.type.equals(String.class)); if (!fd.primitive) throw new RuntimeException("Not compact-serializable getter type: " + (fd.type == null ? "void" : fd.type.getSimpleName())); fd.accessor = method; gettersOnly.add(fd); } } }
From source file:org.jboss.dashboard.commons.misc.ReflectionUtils.java
public static Field getField(Object obj, String propertyName) { try {/*from ww w. j a va2 s .co m*/ Field field = obj.getClass().getField(propertyName); int modifiers = field.getModifiers(); if (Modifier.isPublic(modifiers) && !Modifier.isFinal(field.getModifiers())) { return field; } } catch (NoSuchFieldException e) { } return null; }
From source file:org.apache.syncope.core.logic.LoggerLogic.java
@PreAuthorize("hasRole('" + StandardEntitlement.AUDIT_LIST + "') or hasRole('" + StandardEntitlement.NOTIFICATION_LIST + "')") public List<EventCategoryTO> listAuditEvents() { // use set to avoid duplications or null elements Set<EventCategoryTO> events = new HashSet<>(); try {/*from w w w .j a va 2s.c o m*/ ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver); String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath( SystemPropertyUtils.resolvePlaceholders(this.getClass().getPackage().getName())) + "/**/*.class"; Resource[] resources = resourcePatternResolver.getResources(packageSearchPath); for (Resource resource : resources) { if (resource.isReadable()) { final MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource); final Class<?> clazz = Class.forName(metadataReader.getClassMetadata().getClassName()); if (clazz.isAnnotationPresent(Component.class) && AbstractLogic.class.isAssignableFrom(clazz)) { EventCategoryTO eventCategoryTO = new EventCategoryTO(); eventCategoryTO.setCategory(clazz.getSimpleName()); for (Method method : clazz.getDeclaredMethods()) { if (Modifier.isPublic(method.getModifiers())) { eventCategoryTO.getEvents().add(method.getName()); } } events.add(eventCategoryTO); } } } // SYNCOPE-608 EventCategoryTO authenticationControllerEvents = new EventCategoryTO(); authenticationControllerEvents.setCategory(AuditElements.AUTHENTICATION_CATEGORY); authenticationControllerEvents.getEvents().add(AuditElements.LOGIN_EVENT); events.add(authenticationControllerEvents); events.add(new EventCategoryTO(EventCategoryType.PROPAGATION)); events.add(new EventCategoryTO(EventCategoryType.PULL)); events.add(new EventCategoryTO(EventCategoryType.PUSH)); for (AnyTypeKind anyTypeKind : AnyTypeKind.values()) { for (ExternalResource resource : resourceDAO.findAll()) { EventCategoryTO propEventCategoryTO = new EventCategoryTO(EventCategoryType.PROPAGATION); EventCategoryTO syncEventCategoryTO = new EventCategoryTO(EventCategoryType.PULL); EventCategoryTO pushEventCategoryTO = new EventCategoryTO(EventCategoryType.PUSH); propEventCategoryTO.setCategory(anyTypeKind.name().toLowerCase()); propEventCategoryTO.setSubcategory(resource.getKey()); syncEventCategoryTO.setCategory(anyTypeKind.name().toLowerCase()); pushEventCategoryTO.setCategory(anyTypeKind.name().toLowerCase()); syncEventCategoryTO.setSubcategory(resource.getKey()); pushEventCategoryTO.setSubcategory(resource.getKey()); for (ResourceOperation resourceOperation : ResourceOperation.values()) { propEventCategoryTO.getEvents().add(resourceOperation.name().toLowerCase()); syncEventCategoryTO.getEvents().add(resourceOperation.name().toLowerCase()); pushEventCategoryTO.getEvents().add(resourceOperation.name().toLowerCase()); } for (UnmatchingRule unmatching : UnmatchingRule.values()) { String event = UnmatchingRule.toEventName(unmatching); syncEventCategoryTO.getEvents().add(event); pushEventCategoryTO.getEvents().add(event); } for (MatchingRule matching : MatchingRule.values()) { String event = MatchingRule.toEventName(matching); syncEventCategoryTO.getEvents().add(event); pushEventCategoryTO.getEvents().add(event); } events.add(propEventCategoryTO); events.add(syncEventCategoryTO); events.add(pushEventCategoryTO); } } for (SchedTask task : taskDAO.<SchedTask>findAll(TaskType.SCHEDULED)) { EventCategoryTO eventCategoryTO = new EventCategoryTO(EventCategoryType.TASK); eventCategoryTO.setCategory(Class.forName(task.getJobDelegateClassName()).getSimpleName()); events.add(eventCategoryTO); } EventCategoryTO eventCategoryTO = new EventCategoryTO(EventCategoryType.TASK); eventCategoryTO.setCategory(PullJobDelegate.class.getSimpleName()); events.add(eventCategoryTO); eventCategoryTO = new EventCategoryTO(EventCategoryType.TASK); eventCategoryTO.setCategory(PushJobDelegate.class.getSimpleName()); events.add(eventCategoryTO); } catch (Exception e) { LOG.error("Failure retrieving audit/notification events", e); } return new ArrayList<>(events); }
From source file:com.link_intersystems.lang.reflect.criteria.MemberCriteriaTest.java
@Test public void protecedConstructors() { memberCriteria.membersOfType(Constructor.class); memberCriteria.withAccess(AccessType.PROTECTED); ClassCriteria classCriteria = new ClassCriteria(); Iterable<Class<?>> classIterable = classCriteria.getIterable(ArrayList.class); Iterable<Member> memberIterable = memberCriteria.getIterable(classIterable); assertTrue(memberIterable.iterator().hasNext()); for (Member member : memberIterable) { assertTrue("member must be a constructor", member instanceof Constructor<?>); int modifiers = member.getModifiers(); assertFalse(Modifier.isPublic(modifiers)); assertTrue(Modifier.isProtected(modifiers)); assertFalse(Modifier.isPrivate(modifiers)); }/* www. ja va2 s. c o m*/ }
From source file:com.xie.javacase.json.JSONObject.java
private void populateInternalMap(Object bean, boolean includeSuperClass) { Class klass = bean.getClass(); /* If klass.getSuperClass is System class then force includeSuperClass to false. */ if (klass.getClassLoader() == null) { includeSuperClass = false;// w w w.ja va2 s . c om } 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")) { 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(); } else if (!Character.isUpperCase(key.charAt(1))) { key = key.substring(0, 1).toLowerCase() + key.substring(1); } Object result = method.invoke(bean, (Object[]) null); if (result == null) { map.put(key, NULL); } else if (result.getClass().isArray()) { map.put(key, new JSONArray(result, includeSuperClass)); } else if (result instanceof Collection) { // List or Set map.put(key, new JSONArray((Collection) result, includeSuperClass)); } else if (result instanceof Map) { map.put(key, new JSONObject((Map) result, includeSuperClass)); } else if (isStandardProperty(result.getClass())) { // Primitives, String and Wrapper map.put(key, result); } else { if (result.getClass().getPackage().getName().startsWith("java") || result.getClass().getClassLoader() == null) { map.put(key, result.toString()); } else { // User defined Objects map.put(key, new JSONObject(result, includeSuperClass)); } } } } } catch (Exception e) { throw new RuntimeException(e); } } }
From source file:org.apache.felix.webconsole.AbstractWebConsolePlugin.java
/** * Returns a method which is called on the * {@link #getResourceProvider() resource provider} class to return an URL * to a resource which may be spooled when requested. The method has the * following signature://from w ww. ja v a2 s . com * <pre> * [modifier] URL getResource(String path); * </pre> * Where the <i>[modifier]</i> may be <code>public</code>, <code>protected</code> * or <code>private</code> (if the method is declared in the class of the * resource provider). It is suggested to use the <code>private</code> * modifier if the method is declared in the resource provider class or * the <code>protected</code> modifier if the method is declared in a * base class of the resource provider. * * @return The <code>getResource(String)</code> method or <code>null</code> * if the {@link #getResourceProvider() resource provider} is * <code>null</code> or does not provide such a method. */ private final Method getGetResourceMethod() { // return what we know of the getResourceMethod, if we already checked if (getResourceMethodChecked) { return getResourceMethod; } Method tmpGetResourceMethod = null; Object resourceProvider = getResourceProvider(); if (resourceProvider != null) { try { Class cl = resourceProvider.getClass(); while (tmpGetResourceMethod == null && cl != Object.class) { Method[] methods = cl.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { Method m = methods[i]; if (GET_RESOURCE_METHOD_NAME.equals(m.getName()) && m.getParameterTypes().length == 1 && m.getParameterTypes()[0] == String.class && m.getReturnType() == URL.class) { // ensure modifier is protected or public or the private // method is defined in the plugin class itself int mod = m.getModifiers(); if (Modifier.isProtected(mod) || Modifier.isPublic(mod) || (Modifier.isPrivate(mod) && cl == resourceProvider.getClass())) { m.setAccessible(true); tmpGetResourceMethod = m; break; } } } cl = cl.getSuperclass(); } } catch (Throwable t) { tmpGetResourceMethod = null; } } // set what we have found and prevent future lookups getResourceMethod = tmpGetResourceMethod; getResourceMethodChecked = true; // now also return the method return getResourceMethod; }
From source file:com.link_intersystems.lang.reflect.criteria.MemberCriteria.java
/** * Set the criterion that selects only {@link Member}s that exactly have the * specified modifiers. The access modifiers are set separately. Use * {@link #withAccess(AccessType...)} to set access modifiers. * * @param modifiers// w ww.java 2 s.c o m * @since 1.0.0.0 */ public void withModifiers(int modifiers) { if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers) || Modifier.isPrivate(modifiers)) { throw new IllegalArgumentException( "access modifiers are not allowed as argument. Use withAccess() instead."); } int allowedModifiers = Modifier.ABSTRACT | Modifier.STATIC | Modifier.FINAL | Modifier.TRANSIENT | Modifier.VOLATILE | Modifier.SYNCHRONIZED | Modifier.NATIVE | Modifier.STRICT | Modifier.INTERFACE; if ((modifiers & allowedModifiers) == 0) { throw new IllegalArgumentException( "modifiers must be one of [" + Modifier.toString(allowedModifiers) + "]"); } this.modifiers = modifiers; }
From source file:org.apache.axis2.description.java2wsdl.DefaultSchemaGenerator.java
protected Method[] processMethods(Method[] declaredMethods) throws Exception { ArrayList<Method> list = new ArrayList<Method>(); //short the elements in the array Arrays.sort(declaredMethods, new MathodComparator()); // since we do not support overload HashMap<String, Method> uniqueMethods = new LinkedHashMap<String, Method>(); XmlSchemaComplexType methodSchemaType; XmlSchemaSequence sequence = null;//ww w. jav a 2 s . c om for (Method jMethod : declaredMethods) { if (jMethod.isBridge()) { continue; } WebMethodAnnotation methodAnnon = JSR181Helper.INSTANCE.getWebMethodAnnotation(jMethod); String methodName = jMethod.getName(); if (methodAnnon != null) { if (methodAnnon.isExclude()) { continue; } if (methodAnnon.getOperationName() != null) { methodName = methodAnnon.getOperationName(); } } // no need to think abt this method , since that is system // config method if (excludeMethods.contains(methodName)) { continue; } if (!Modifier.isPublic(jMethod.getModifiers())) { // no need to generate Schema for non public methods continue; } if (uniqueMethods.get(methodName) != null) { log.warn("We don't support method overloading. Ignoring [" + methodName + "]"); continue; } boolean addToService = false; AxisOperation axisOperation = service.getOperation(new QName(methodName)); if (axisOperation == null) { axisOperation = Utils.getAxisOperationForJmethod(jMethod); // if (WSDL2Constants.MEP_URI_ROBUST_IN_ONLY.equals( // axisOperation.getMessageExchangePattern())) { // AxisMessage outMessage = axisOperation.getMessage( // WSDLConstants.MESSAGE_LABEL_OUT_VALUE); // if (outMessage != null) { // outMessage.setName(methodName + RESPONSE); // } // } addToService = true; } // by now axis operation should be assigned but we better recheck & add the paramether if (axisOperation != null) { axisOperation.addParameter("JAXRSAnnotaion", JAXRSUtils.getMethodModel(this.classModel, jMethod)); } // Maintain a list of methods we actually work with list.add(jMethod); processException(jMethod, axisOperation); uniqueMethods.put(methodName, jMethod); Class<?>[] parameters = jMethod.getParameterTypes(); String parameterNames[] = null; AxisMessage inMessage = axisOperation.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE); if (inMessage != null) { inMessage.setName(methodName + Java2WSDLConstants.MESSAGE_SUFFIX); } if (parameters.length > 0) { parameterNames = methodTable.getParameterNames(methodName); // put the parameter names to use it for parsing service.addParameter(methodName, parameterNames); } // we need to add the method opration wrapper part even to // empty parameter operations sequence = new XmlSchemaSequence(); String requestElementSuffix = getRequestElementSuffix(); String requestLocalPart = methodName; if (requestElementSuffix != null) { requestLocalPart += requestElementSuffix; } methodSchemaType = createSchemaTypeForMethodPart(requestLocalPart); methodSchemaType.setParticle(sequence); inMessage.setElementQName(typeTable.getQNamefortheType(requestLocalPart)); Parameter param = service.getParameter(Java2WSDLConstants.MESSAGE_PART_NAME_OPTION_LONG); if (param != null) { inMessage.setPartName((String) param.getValue()); } service.addMessageElementQNameToOperationMapping(methodSchemaType.getQName(), axisOperation); Annotation[][] parameterAnnotation = jMethod.getParameterAnnotations(); Type[] genericParameterTypes = jMethod.getGenericParameterTypes(); for (int j = 0; j < parameters.length; j++) { Class<?> methodParameter = parameters[j]; String parameterName = getParameterName(parameterAnnotation, j, parameterNames); if (nonRpcMethods.contains(jMethod.getName())) { generateSchemaForType(sequence, null, jMethod.getName()); break; } else { Type genericParameterType = genericParameterTypes[j]; Type genericType = null; if (genericParameterType instanceof ParameterizedType) { ParameterizedType aType = (ParameterizedType) genericParameterType; Type[] parameterArgTypes = aType.getActualTypeArguments(); genericType = parameterArgTypes[0]; generateSchemaForType(sequence, genericType, parameterName, true); } else { generateSchemaForType(sequence, methodParameter, parameterName); } } } // for its return type Class<?> returnType = jMethod.getReturnType(); if (!"void".equals(jMethod.getReturnType().getName())) { String partQname = methodName + RESPONSE; methodSchemaType = createSchemaTypeForMethodPart(partQname); sequence = new XmlSchemaSequence(); methodSchemaType.setParticle(sequence); WebResultAnnotation returnAnnon = JSR181Helper.INSTANCE.getWebResultAnnotation(jMethod); String returnName = "return"; if (returnAnnon != null) { returnName = returnAnnon.getName(); if (returnName == null || "".equals(returnName)) { returnName = "return"; } } Type genericParameterType = jMethod.getGenericReturnType(); if (nonRpcMethods.contains(jMethod.getName())) { generateSchemaForType(sequence, null, returnName); } else if (genericParameterType instanceof ParameterizedType) { ParameterizedType aType = (ParameterizedType) genericParameterType; Type[] parameterArgTypes = aType.getActualTypeArguments(); generateSchemaForType(sequence, parameterArgTypes[0], returnName, true); } else { generateSchemaForType(sequence, returnType, returnName); } AxisMessage outMessage = axisOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE); outMessage.setElementQName(typeTable.getQNamefortheType(partQname)); outMessage.setName(partQname); Parameter outparam = service.getParameter(Java2WSDLConstants.MESSAGE_PART_NAME_OPTION_LONG); if (outparam != null) { outMessage.setPartName((String) outparam.getValue()); } service.addMessageElementQNameToOperationMapping(methodSchemaType.getQName(), axisOperation); } if (addToService) { service.addOperation(axisOperation); } } return list.toArray(new Method[list.size()]); }