List of usage examples for java.lang.reflect Modifier isPublic
public static boolean isPublic(int mod)
From source file:org.apache.tajo.engine.function.FunctionLoader.java
private static boolean isPublicStaticMethod(Method method) { return Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers()); }
From source file:com.vecna.taglib.processor.JspAnnotationsProcessor.java
/** * Build JSP function models from an annotated class * @param type class with annotated static methods * @return JSP function models/*from ww w .java 2 s. c om*/ */ public Collection<JspFunctionModel> getFunctionMetadata(Class<?> type) { Collection<JspFunctionModel> functions = new ArrayList<JspFunctionModel>(); for (Method method : type.getMethods()) { if (Modifier.isStatic(method.getModifiers()) && Modifier.isPublic(method.getModifiers()) && method.isAnnotationPresent(JspFunction.class)) { JspFunction functionAnnotation = method.getAnnotation(JspFunction.class); JspFunctionModel metadata = new JspFunctionModel(); metadata.name = functionAnnotation.name(); metadata.functionClass = type.getName(); JspFunctionSignature signature = new JspFunctionSignature(); signature.name = method.getName(); signature.argumentTypes = method.getParameterTypes(); signature.returnType = method.getReturnType(); metadata.signature = signature; functions.add(metadata); } } return functions; }
From source file:org.codehaus.marmalade.el.commonsEl.CommonsElExpressionEvaluator.java
private Object set(Object target, String property, Object value) throws ExpressionEvaluationException { Object result = null;/*from w w w . j a v a 2s .c o m*/ try { Method method = findMethod(target, property, value); if (method != null) { result = method.invoke(target, new Object[] { value }); } else { Field field = target.getClass().getField(property); int fieldModifiers = field.getModifiers(); if (Modifier.isPublic(fieldModifiers) && !Modifier.isFinal(fieldModifiers) && field.getType().isAssignableFrom(value.getClass())) { field.set(target, value); result = value; } else { throw new ExpressionEvaluationException( "Cannot set property: \'" + property + "\' on target: " + target); } } } catch (IllegalArgumentException e) { throw new ExpressionEvaluationException("Error assigning value to property field.", e); } catch (IllegalAccessException e) { throw new ExpressionEvaluationException("Error assigning value to property field.", e); } catch (SecurityException e) { throw new ExpressionEvaluationException("Error assigning value to property field.", e); } catch (NoSuchFieldException e) { throw new ExpressionEvaluationException("Property not found: \'" + property + "\' on target: " + target, e); } catch (InvocationTargetException e) { throw new ExpressionEvaluationException("Error assigning value via property method.", e); } return result; }
From source file:com.weibo.api.motan.config.springsupport.MotanBeanDefinitionParser.java
@SuppressWarnings({ "rawtypes", "unchecked" }) private static BeanDefinition parse(Element element, ParserContext parserContext, Class<?> beanClass, boolean required) throws ClassNotFoundException { RootBeanDefinition bd = new RootBeanDefinition(); bd.setBeanClass(beanClass);//w ww . j av a 2s.co m // ??lazy init bd.setLazyInit(false); // id?id,idcontext String id = element.getAttribute("id"); if ((id == null || id.length() == 0) && required) { String generatedBeanName = element.getAttribute("name"); if (generatedBeanName == null || generatedBeanName.length() == 0) { generatedBeanName = element.getAttribute("class"); } if (generatedBeanName == null || generatedBeanName.length() == 0) { generatedBeanName = beanClass.getName(); } id = generatedBeanName; int counter = 2; while (parserContext.getRegistry().containsBeanDefinition(id)) { id = generatedBeanName + (counter++); } } if (id != null && id.length() > 0) { if (parserContext.getRegistry().containsBeanDefinition(id)) { throw new IllegalStateException("Duplicate spring bean id " + id); } parserContext.getRegistry().registerBeanDefinition(id, bd); } bd.getPropertyValues().addPropertyValue("id", id); if (ProtocolConfig.class.equals(beanClass)) { MotanNamespaceHandler.protocolDefineNames.add(id); } else if (RegistryConfig.class.equals(beanClass)) { MotanNamespaceHandler.registryDefineNames.add(id); } else if (BasicServiceInterfaceConfig.class.equals(beanClass)) { MotanNamespaceHandler.basicServiceConfigDefineNames.add(id); } else if (BasicRefererInterfaceConfig.class.equals(beanClass)) { MotanNamespaceHandler.basicRefererConfigDefineNames.add(id); } else if (ServiceConfigBean.class.equals(beanClass)) { String className = element.getAttribute("class"); if (className != null && className.length() > 0) { RootBeanDefinition classDefinition = new RootBeanDefinition(); classDefinition.setBeanClass( Class.forName(className, true, Thread.currentThread().getContextClassLoader())); classDefinition.setLazyInit(false); parseProperties(element.getChildNodes(), classDefinition); bd.getPropertyValues().addPropertyValue("ref", new BeanDefinitionHolder(classDefinition, id + "Impl")); } } Set<String> props = new HashSet<String>(); ManagedMap parameters = null; // ??setbd for (Method setter : beanClass.getMethods()) { String name = setter.getName(); // setXXX if (name.length() <= 3 || !name.startsWith("set") || !Modifier.isPublic(setter.getModifiers()) || setter.getParameterTypes().length != 1) { continue; } String property = (name.substring(3, 4).toLowerCase() + name.substring(4)).replaceAll("_", "-"); props.add(property); if ("id".equals(property)) { bd.getPropertyValues().addPropertyValue("id", id); continue; } String value = element.getAttribute(property); if ("methods".equals(property)) { parseMethods(id, element.getChildNodes(), bd, parserContext); } if (StringUtils.isBlank(value)) { continue; } value = value.trim(); if (value.length() == 0) { continue; } Object reference; if ("ref".equals(property)) { if (parserContext.getRegistry().containsBeanDefinition(value)) { BeanDefinition refBean = parserContext.getRegistry().getBeanDefinition(value); if (!refBean.isSingleton()) { throw new IllegalStateException( "The exported service ref " + value + " must be singleton! Please set the " + value + " bean scope to singleton, eg: <bean id=\"" + value + "\" scope=\"singleton\" ...>"); } } reference = new RuntimeBeanReference(value); } else if ("protocol".equals(property) && !StringUtils.isBlank(value)) { if (!value.contains(",")) { reference = new RuntimeBeanReference(value); } else { parseMultiRef("protocols", value, bd, parserContext); reference = null; } } else if ("registry".equals(property)) { parseMultiRef("registries", value, bd, parserContext); reference = null; } else if ("basicService".equals(property)) { reference = new RuntimeBeanReference(value); } else if ("basicReferer".equals(property)) { reference = new RuntimeBeanReference(value); } else if ("extConfig".equals(property)) { reference = new RuntimeBeanReference(value); } else { reference = new TypedStringValue(value); } if (reference != null) { bd.getPropertyValues().addPropertyValue(property, reference); } } if (ProtocolConfig.class.equals(beanClass)) { // protocolparameters? NamedNodeMap attributes = element.getAttributes(); int len = attributes.getLength(); for (int i = 0; i < len; i++) { Node node = attributes.item(i); String name = node.getLocalName(); if (!props.contains(name)) { if (parameters == null) { parameters = new ManagedMap(); } String value = node.getNodeValue(); parameters.put(name, new TypedStringValue(value, String.class)); } } bd.getPropertyValues().addPropertyValue("parameters", parameters); } return bd; }
From source file:com.haulmont.cuba.core.config.type.TypeFactory.java
@Nullable private static TypeFactory getInferred(Class<?> returnType) { // special case due to Character.valueOf(char) does not accept String if (returnType == Character.class) { return new CharTypeFactory(); }/*from w w w. j a va2 s . c o m*/ for (String methodName : FACTORY_METHOD_NAMES) { try { Method factoryMethod = returnType.getMethod(methodName, String.class); if (isAcceptableMethod(returnType, factoryMethod)) { return new StaticTypeFactory(factoryMethod); } } catch (NoSuchMethodException ex) { // Ignore failure. } } try { Constructor ctor = returnType.getConstructor(String.class); if (Modifier.isPublic(ctor.getModifiers())) { return new ConstructorTypeFactory(ctor); } } catch (NoSuchMethodException e) { return null; } return null; }
From source file:org.springframework.boot.test.web.client.TestRestTemplateTests.java
@Test public void restOperationsAreAvailable() throws Exception { RestTemplate delegate = mock(RestTemplate.class); given(delegate.getUriTemplateHandler()).willReturn(new DefaultUriBuilderFactory()); final TestRestTemplate restTemplate = new TestRestTemplate(delegate); ReflectionUtils.doWithMethods(RestOperations.class, new MethodCallback() { @Override/*from ww w. j a va2 s. c o m*/ public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { Method equivalent = ReflectionUtils.findMethod(TestRestTemplate.class, method.getName(), method.getParameterTypes()); assertThat(equivalent).as("Method %s not found", method).isNotNull(); assertThat(Modifier.isPublic(equivalent.getModifiers())) .as("Method %s should have been public", equivalent).isTrue(); try { equivalent.invoke(restTemplate, mockArguments(method.getParameterTypes())); } catch (Exception ex) { throw new IllegalStateException(ex); } } private Object[] mockArguments(Class<?>[] parameterTypes) throws Exception { Object[] arguments = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { arguments[i] = mockArgument(parameterTypes[i]); } return arguments; } @SuppressWarnings("rawtypes") private Object mockArgument(Class<?> type) throws Exception { if (String.class.equals(type)) { return "String"; } if (Object[].class.equals(type)) { return new Object[0]; } if (URI.class.equals(type)) { return new URI("http://localhost"); } if (HttpMethod.class.equals(type)) { return HttpMethod.GET; } if (Class.class.equals(type)) { return Object.class; } if (RequestEntity.class.equals(type)) { return new RequestEntity(HttpMethod.GET, new URI("http://localhost")); } return mock(type); } }, (method) -> Modifier.isPublic(method.getModifiers())); }
From source file:no.abmu.util.reflection.FieldUtil.java
public static boolean setFieldValue(Object obj, String fieldName, Object value) { Assert.checkRequiredArgument("obj", obj); Assert.checkRequiredArgument("fieldName", fieldName); String errorMessage = "Object '" + obj.getClass().getName() + " does not have field/variable with name '" + fieldName + "'"; Assert.assertTrue(errorMessage, hasObjectVariable(obj, fieldName)); Field field = getField(obj, fieldName); boolean sucess = false; try {//from w ww . j ava 2 s. c om if (Modifier.isPublic(field.getModifiers())) { field.set(obj, value); } else { field.setAccessible(true); field.set(obj, value); field.setAccessible(false); } sucess = true; } catch (IllegalAccessException e) { logger.warn(e.getMessage()); } return sucess; }
From source file:org.apache.velocity.util.introspection.ClassMap.java
/** * Populate the Map of direct hits. These * are taken from all the public methods * that our class, its parents and their implemented interfaces provide. *///w w w .j av a 2s . c o m private MethodCache createMethodCache() { MethodCache methodCache = new MethodCache(); // // Looks through all elements in the class hierarchy. This one is bottom-first (i.e. we start // with the actual declaring class and its interfaces and then move up (superclass etc.) until we // hit java.lang.Object. That is important because it will give us the methods of the declaring class // which might in turn be abstract further up the tree. // // We also ignore all SecurityExceptions that might happen due to SecurityManager restrictions (prominently // hit with Tomcat 5.5). // // We can also omit all that complicated getPublic, getAccessible and upcast logic that the class map had up // until Velocity 1.4. As we always reflect all elements of the tree (that's what we have a cache for), we will // hit the public elements sooner or later because we reflect all the public elements anyway. // // Ah, the miracles of Java for(;;) ... for (Class classToReflect = getCachedClass(); classToReflect != null; classToReflect = classToReflect .getSuperclass()) { if (Modifier.isPublic(classToReflect.getModifiers())) { populateMethodCacheWith(methodCache, classToReflect); } Class[] interfaces = classToReflect.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { populateMethodCacheWithInterface(methodCache, interfaces[i]); } } // return the already initialized cache return methodCache; }
From source file:gobblin.runtime.cli.ConstructorAndPublicMethodsGobblinCliFactory.java
private boolean canUseConstructor(Constructor<?> constructor) { if (!Modifier.isPublic(constructor.getModifiers())) { return false; }// w w w .j av a2 s .c o m if (!constructor.isAnnotationPresent(EmbeddedGobblinCliSupport.class)) { return false; } for (Class<?> param : constructor.getParameterTypes()) { if (param != String.class) { return false; } } return constructor.getParameterTypes().length == constructor.getAnnotation(EmbeddedGobblinCliSupport.class) .argumentNames().length; }
From source file:jef.tools.reflect.ClassEx.java
Object innerInvoke(Object obj, String method, boolean isStatic, Object... params) throws ReflectionException { try {/*from w w w. j av a 2s . c o m*/ if (obj == null && !isStatic) obj = newInstance(); List<Class<?>> list = new ArrayList<Class<?>>(); for (Object pobj : params) { list.add(pobj.getClass()); } MethodEx me = BeanUtils.getCompatibleMethod(cls, method, list.toArray(new Class[list.size()])); if (me == null) { NoSuchMethodException e = new NoSuchMethodException("Method:[" + cls.getName() + "::" + method + "] not found with param count:" + params.length); throw new ReflectionException(e); } if (!Modifier.isPublic(me.getModifiers()) || !Modifier.isPublic(cls.getModifiers())) { try { me.setAccessible(true); } catch (SecurityException e) { System.out.println(me.toString() + "\n" + e.getMessage()); } } return me.invoke(obj, params); } catch (IllegalAccessException e) { throw new ReflectionException(e); } catch (SecurityException e) { throw new ReflectionException(e); } catch (IllegalArgumentException e) { throw new ReflectionException(e); } catch (InvocationTargetException e) { if (e.getCause() instanceof Exception) { throw new ReflectionException((Exception) e.getCause()); } else { throw new ReflectionException(e); } } }