List of usage examples for java.lang.reflect Modifier isPublic
public static boolean isPublic(int mod)
From source file:me.rojo8399.placeholderapi.impl.utils.TypeUtils.java
@SuppressWarnings("unchecked") public static <T> Optional<T> tryCast(Object val, final Class<T> expected) { if (val == null) { return Optional.empty(); }//from w ww. jav a2 s . c o m if (expected == null) { throw new IllegalArgumentException("Must provide an expected class!"); } if (val instanceof BaseValue<?> && !BaseValue.class.isAssignableFrom(expected)) { return tryCast(((BaseValue<?>) val).get(), expected); } if (val instanceof Supplier) { Supplier<?> fun = (Supplier<?>) val; return tryCast(fun.get(), expected); } if (Text.class.isAssignableFrom(expected)) { if (val instanceof Text) { return TypeUtils.tryOptional(() -> expected.cast(val)); } else { if (val instanceof ItemStack) { return TypeUtils.tryOptional(() -> expected.cast(TextUtils.ofItem((ItemStack) val))); } if (val instanceof Instant) { return TypeUtils.tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE .deserialize(PlaceholderAPIPlugin.getInstance().formatter() .format(LocalDateTime.ofInstant((Instant) val, ZoneId.systemDefault()))))); } if (val instanceof Duration) { String dur = formatDuration((Duration) val); return TypeUtils .tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE.deserialize(dur))); } if (val instanceof LocalDateTime) { return TypeUtils.tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE.deserialize( PlaceholderAPIPlugin.getInstance().formatter().format((LocalDateTime) val)))); } if (val instanceof CommandSource) { return TypeUtils.tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE .deserialize(String.valueOf(((CommandSource) val).getName())))); } if (val.getClass().isArray()) { List<Text> l2 = unboxPrimitiveArray(val).stream() .map(o -> tryCast(o, (Class<? extends Text>) expected)).flatMap(unmapOptional()) .collect(Collectors.toList()); return TypeUtils.tryOptional(() -> expected.cast(Text.joinWith(Text.of(", "), l2))); } if (val instanceof Iterable) { Iterable<?> l = (Iterable<?>) val; // should be safe cause we already checked assignability @SuppressWarnings("serial") final List<Text> l2 = new ArrayList<Object>() { { for (Object o : l) { add(o); } } }.stream().map(o -> tryCast(o, (Class<? extends Text>) expected)).flatMap(unmapOptional()) .collect(Collectors.toList()); return TypeUtils.tryOptional(() -> expected.cast(Text.joinWith(Text.of(", "), l2))); } return TypeUtils.tryOptional( () -> expected.cast(TextSerializers.FORMATTING_CODE.deserialize(String.valueOf(val)))); } } if (val instanceof String) { if (String.class.isAssignableFrom(expected)) { return tryOptional(() -> expected.cast(val)); } if (expected.isArray() && String.class.isAssignableFrom(expected.getComponentType())) { String v = (String) val; if (v.isEmpty()) { return Optional.empty(); } if (!v.contains("_")) { return tryOptional(() -> expected.cast(new String[] { v })); } String[] x = v.split("_"); if (x.length == 0) { return Optional.empty(); } boolean ne = false; for (String s : x) { ne = ne || !s.isEmpty(); } if (!ne) { return Optional.empty(); } return tryOptional(() -> expected.cast(x)); } if (List.class.isAssignableFrom(expected) && String.class.isAssignableFrom(expected.getTypeParameters()[0].getGenericDeclaration())) { String v = (String) val; if (v.isEmpty()) { return Optional.empty(); } if (!v.contains("_")) { return tryOptional(() -> expected.cast(Collections.singletonList(v))); } String[] x = v.split("_"); if (x.length == 0) { return Optional.empty(); } boolean ne = false; for (String s : x) { ne = ne || !s.isEmpty(); } if (!ne) { return Optional.empty(); } return tryOptional(() -> expected.cast(Arrays.asList(x))); } Optional<T> opt = tryOptional(() -> convertPrimitive((String) val, expected)); if (opt.isPresent()) { return opt; } opt = deserializers.entrySet().stream() .filter(e -> e.getKey().isSubtypeOf(expected) || e.getKey().getRawType().equals(expected)) .map(Map.Entry::getValue).map(f -> tryOptional(() -> f.apply((String) val))) .flatMap(unmapOptional()).findAny().flatMap(o -> tryOptional(() -> expected.cast(o))); if (opt.isPresent()) { return opt; } try { // should theoretically match any string -> object conversions, such as deser // for now im filtering against method names as well just to avoid issues where // expected result is not obtained due to weird methods, might change in future Method method = Arrays.stream(expected.getDeclaredMethods()) .filter(m -> Modifier.isStatic(m.getModifiers()) && Modifier.isPublic(m.getModifiers())) .filter(m -> Arrays.stream(m.getParameterTypes()).anyMatch(c -> c.equals(String.class))) .filter(m -> m.getReturnType().equals(expected) || m.getReturnType().equals(Optional.class)) .filter(m -> STRING_TO_VAL_PATTERN.matcher(m.getName()).find()).findAny().get(); // error if no Object valout = method.invoke(null, (String) val); if (valout == null) { return Optional.empty(); } if (expected.isInstance(valout)) { // Register a new deserializer once we confirm it works. Should prevent // extremely long parsing from happening multiple times. final MethodHandle mh = MethodHandles.publicLookup().unreflect(method); PlaceholderServiceImpl.get().registerTypeDeserializer(TypeToken.of(expected), str -> { try { return expected.cast(mh.invokeExact((String) val)); } catch (Throwable e1) { throw new RuntimeException(e1); } }); return tryOptional(() -> expected.cast(valout)); } if (valout instanceof Optional) { Optional<?> valopt = (Optional<?>) valout; if (!valopt.isPresent()) { return Optional.empty(); } Object v = valopt.get(); if (expected.isInstance(v)) { // Register a new deserializer once we confirm it works. Should prevent // extremely long parsing from happening multiple times. final MethodHandle mh = MethodHandles.publicLookup().unreflect(method); PlaceholderServiceImpl.get().registerTypeDeserializer(TypeToken.of(expected), str -> { try { Optional<?> optx = (Optional<?>) mh.invokeExact((String) val); return expected.cast(optx.get()); } catch (Throwable e1) { throw new RuntimeException(e1); } }); return tryOptional(() -> expected.cast(v)); } else { return Optional.empty(); } } return Optional.empty(); } catch (Exception e) { // fires if no method found, if invoke throws, if something else goes wrong return Optional.empty(); } } return TypeUtils.tryOptional(() -> expected.cast(val)); }
From source file:com.strandls.alchemy.rest.client.AlchemyRestClientFactoryTest.java
/** * Test method for/*from www .ja v a 2s . c o m*/ * {@link com.strandls.alchemy.rest.client.AlchemyRestClientFactory#getInstance(java.lang.Class, java.lang.String, javax.ws.rs.client.Client)} * . * * Test get and post methods with a combination of parameter types (query, * path, header, cookie, matrix) * * @throws Exception */ @Test public void testGetInstanceGetAndPost() throws Exception { final TestWebserviceWithPath service = clientFactory.getInstance(TestWebserviceWithPath.class); final Random r = new Random(); final int[] args = new int[] { r.nextInt(), r.nextInt(), r.nextInt() }; @SuppressWarnings("unchecked") final Set<Method> methods = ReflectionUtils.getAllMethods(TestWebserviceWithPath.class, new Predicate<Method>() { @Override public boolean apply(final Method input) { return Modifier.isPublic(input.getModifiers()); } }); for (final Method method : methods) { System.out.println("Invoking : " + method); if (method.getParameterTypes().length == 3) { assertArrayEquals("Invocation failed on " + method, args, (int[]) method.invoke(service, args[0], args[1], args[2])); } else if (method.getParameterTypes().length == 0) { method.invoke(service); } else { assertArrayEquals("Invocation failed on " + method, args, (int[]) method.invoke(service, args)); } System.out.println("Done invoking : " + method); } }
From source file:com.github.venkateshamurthy.designpatterns.builders.FluentBuilders.java
/** * Gets a list of writable methods / mutator methods. <br> * //from w w w . java 2 s . c o m * @param thisPojoClass * for which mutator methods must be found * @return List of {@link CtMethod} * @throws NotFoundException * when thisPojoClass is not found */ private Set<CtMethod> getWritableMethods(final Class<?> thisPojoClass) throws NotFoundException { final CtClass ctClass = ctPool.get(thisPojoClass.getName()); final Set<CtMethod> ctMethodSet = new LinkedHashSet<>(); // Gets // collected final Set<Class<?>> propTypes = getPropertyClassTypes(thisPojoClass, ctClass, ctMethodSet); for (Method method : thisPojoClass.getDeclaredMethods()) { if (method.isSynthetic()) { LOGGER.warning(method.getName() + " is synthetically added, so ignoring"); continue; } final CtMethod ctMethod = ctClass.getDeclaredMethod(method.getName()); if (Modifier.isPublic(method.getModifiers()) && setMethodNamePattern.matcher(method.getName()).matches() && !ctMethodSet.contains(ctMethod)) { // Make sure the types u get from method is really is of a field // type boolean isAdded = /* * propTypes.containsAll(Arrays.asList(method. * getParameterTypes())) && */ctMethodSet.add(ctMethod); if (!isAdded) { LOGGER.warning(method.getName() + " is not added"); } } } return ctMethodSet; }
From source file:org.evosuite.setup.TestUsageChecker.java
public static boolean canUse(Method m, Class<?> ownerClass) { if (m.isBridge()) { logger.debug("Excluding bridge method: " + m.toString()); return false; }//from w w w .ja v a 2 s . c o m if (m.isSynthetic()) { logger.debug("Excluding synthetic method: " + m.toString()); return false; } if (!Properties.USE_DEPRECATED && m.isAnnotationPresent(Deprecated.class)) { final Class<?> targetClass = Properties.getTargetClassAndDontInitialise(); if (Properties.hasTargetClassBeenLoaded() && !m.getDeclaringClass().equals(targetClass)) { logger.debug("Excluding deprecated method " + m.getName()); return false; } } if (m.isAnnotationPresent(Test.class) || m.isAnnotationPresent(Before.class) || m.isAnnotationPresent(BeforeClass.class) || m.isAnnotationPresent(After.class) || m.isAnnotationPresent(AfterClass.class)) { logger.debug("Excluding test method " + m.getName()); return false; } if (m.isAnnotationPresent(EvoSuiteTest.class)) { logger.debug("Excluding EvoSuite test method " + m.getName()); return false; } if (m.isAnnotationPresent(EvoSuiteExclude.class)) { logger.debug("Excluding method with exclusion annotation " + m.getName()); return false; } if (m.getDeclaringClass().equals(java.lang.Object.class)) { return false; } if (!m.getReturnType().equals(String.class) && (!canUse(m.getReturnType()) || !canUse(m.getGenericReturnType()))) { return false; } for (java.lang.reflect.Type paramType : m.getGenericParameterTypes()) { if (!canUse(paramType)) return false; } if (m.getDeclaringClass().equals(Enum.class)) { return false; /* if (m.getName().equals("valueOf") || m.getName().equals("values") || m.getName().equals("ordinal")) { logger.debug("Excluding valueOf for Enum " + m.toString()); return false; } // Skip compareTo on enums (like Randoop) if (m.getName().equals("compareTo") && m.getParameterTypes().length == 1 && m.getParameterTypes()[0].equals(Enum.class)) return false; */ } if (m.getDeclaringClass().equals(java.lang.Thread.class)) return false; // Hashcode only if we need to cover it if (m.getName().equals("hashCode")) { final Class<?> targetClass = Properties.getTargetClassAndDontInitialise(); if (!m.getDeclaringClass().equals(targetClass)) return false; else { if (GraphPool.getInstance(ownerClass.getClassLoader()).getActualCFG(Properties.TARGET_CLASS, m.getName() + Type.getMethodDescriptor(m)) == null) { // Don't cover generated hashCode // TODO: This should work via annotations return false; } } } // Randoop special case: just clumps together a bunch of hashCodes, so skip it if (m.getName().equals("deepHashCode") && m.getDeclaringClass().equals(Arrays.class)) return false; // Randoop special case: differs too much between JDK installations if (m.getName().equals("getAvailableLocales")) return false; if (m.getName().equals(ClassResetter.STATIC_RESET)) { logger.debug("Ignoring static reset method"); return false; } if (isForbiddenNonDeterministicCall(m)) { return false; } if (!Properties.CONSIDER_MAIN_METHODS && m.getName().equals("main") && Modifier.isStatic(m.getModifiers()) && Modifier.isPublic(m.getModifiers())) { logger.debug("Ignoring static main method "); return false; } /* if(m.getTypeParameters().length > 0) { logger.debug("Cannot handle generic methods at this point"); if(m.getDeclaringClass().equals(Properties.getTargetClass())) { LoggingUtils.getEvoLogger().info("* Skipping method "+m.getName()+": generic methods are not handled yet"); } return false; } */ // If default or if (Modifier.isPublic(m.getModifiers())) { TestClusterUtils.makeAccessible(m); return true; } // If default access rights, then check if this class is in the same package as the target class if (!Modifier.isPrivate(m.getModifiers())) { // && !Modifier.isProtected(m.getModifiers())) { String packageName = ClassUtils.getPackageName(ownerClass); String declaredPackageName = ClassUtils.getPackageName(m.getDeclaringClass()); if (packageName.equals(Properties.CLASS_PREFIX) && packageName.equals(declaredPackageName)) { TestClusterUtils.makeAccessible(m); return true; } } return false; }
From source file:net.abhinavsarkar.spelhelper.SpelHelper.java
private static List<Method> filterMethods(final Class<?> clazz) { List<Method> allowedMethods = new ArrayList<Method>(); for (Method method : clazz.getMethods()) { int modifiers = method.getModifiers(); if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && !method.getReturnType().equals(Void.TYPE) && method.getParameterTypes().length > 0) { allowedMethods.add(method);//from w w w .j a v a2s . c om } } return allowedMethods; }
From source file:cn.webwheel.DefaultMain.java
@SuppressWarnings("unchecked") private void autoMap(String root, String pkg, String name) { Class cls;/* w w w. j a v a2s. com*/ try { cls = Class.forName(pkg + "." + name); } catch (ClassNotFoundException e) { return; } if (cls.isMemberClass() && !Modifier.isStatic(cls.getModifiers())) { return; } if (cls.isAnonymousClass() || cls.isLocalClass() || !Modifier.isPublic(cls.getModifiers()) || Modifier.isAbstract(cls.getModifiers())) { return; } name = name.replace('$', '.'); for (Method method : cls.getMethods()) { String pathPrefix = pkg.substring(root.length()).replace('.', '/') + '/'; String path = pathPrefix + name + '.' + method.getName(); Action action = getAction(cls, method); if (action == null) continue; if (!action.value().isEmpty()) { if (action.value().startsWith("?")) { path = path + action.value(); } else if (action.value().startsWith(".")) { path = pathPrefix + name + action.value(); } else if (!action.value().startsWith("/")) { path = pathPrefix + action.value(); } else { path = action.value(); } } ActionBinder binder = map(path); if (!action.rest().isEmpty()) { String rest = action.rest(); if (!rest.startsWith("/")) rest = pathPrefix + rest; binder = binder.rest(rest); } SetterConfig cfg = binder.with(cls, method); if (!action.charset().isEmpty()) { cfg = cfg.setCharset(action.charset()); } if (action.fileUploadFileSizeMax() != 0) { cfg = cfg.setFileUploadFileSizeMax(action.fileUploadFileSizeMax()); } if (action.fileUploadSizeMax() != 0) { cfg.setFileUploadSizeMax(action.fileUploadSizeMax()); } if (action.setterPolicy() != SetterPolicy.Auto) { cfg.setSetterPolicy(action.setterPolicy()); } } }
From source file:com.judoscript.jamaica.parser.JamaicaDumpVisitor.java
static void printAccessFlags(int flags) { if (Modifier.isPublic(flags)) out.print("public "); else if (Modifier.isProtected(flags)) out.print("protected "); else if (Modifier.isPrivate(flags)) out.print("private "); if (Modifier.isAbstract(flags)) out.print("abstract "); if (Modifier.isFinal(flags)) out.print("final "); if (Modifier.isNative(flags)) out.print("native "); if (Modifier.isStatic(flags)) out.print("static "); if (Modifier.isStrict(flags)) out.print("strict "); if (Modifier.isSynchronized(flags)) out.print("synchronized "); if (Modifier.isTransient(flags)) out.print("transient "); if (Modifier.isVolatile(flags)) out.print("volative "); }
From source file:org.apache.sling.scripting.sightly.impl.engine.runtime.RenderContextImpl.java
private static Method extractMethodInheritanceChain(Class type, Method m) { if (m == null || Modifier.isPublic(type.getModifiers())) { return m; }/*from ww w . j av a 2s .c om*/ Class[] inf = type.getInterfaces(); Method mp; for (Class<?> iface : inf) { try { mp = iface.getMethod(m.getName(), m.getParameterTypes()); mp = extractMethodInheritanceChain(mp.getDeclaringClass(), mp); if (mp != null) { return mp; } } catch (NoSuchMethodException e) { // do nothing } } Class<?> sup = type.getSuperclass(); if (sup != null) { try { mp = sup.getMethod(m.getName(), m.getParameterTypes()); mp = extractMethodInheritanceChain(mp.getDeclaringClass(), mp); if (mp != null) { return mp; } } catch (NoSuchMethodException e) { // do nothing } } return null; }
From source file:net.lightbody.bmp.proxy.jetty.xml.XmlConfiguration.java
private void set(Object obj, XmlParser.Node node) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { String attr = node.getAttribute("name"); String name = "set" + attr.substring(0, 1).toUpperCase() + attr.substring(1); Object value = value(obj, node); Object[] arg = { value };/* www . j av a 2 s . c o m*/ Class oClass = nodeClass(node); if (oClass != null) obj = null; else oClass = obj.getClass(); Class[] vClass = { Object.class }; if (value != null) vClass[0] = value.getClass(); if (log.isDebugEnabled()) log.debug(obj + "." + name + "(" + vClass[0] + " " + value + ")"); // Try for trivial match try { Method set = oClass.getMethod(name, vClass); set.invoke(obj, arg); return; } catch (IllegalArgumentException e) { LogSupport.ignore(log, e); } catch (IllegalAccessException e) { LogSupport.ignore(log, e); } catch (NoSuchMethodException e) { LogSupport.ignore(log, e); } // Try for native match try { Field type = vClass[0].getField("TYPE"); vClass[0] = (Class) type.get(null); Method set = oClass.getMethod(name, vClass); set.invoke(obj, arg); return; } catch (NoSuchFieldException e) { LogSupport.ignore(log, e); } catch (IllegalArgumentException e) { LogSupport.ignore(log, e); } catch (IllegalAccessException e) { LogSupport.ignore(log, e); } catch (NoSuchMethodException e) { LogSupport.ignore(log, e); } // Try a field try { Field field = oClass.getField(attr); if (Modifier.isPublic(field.getModifiers())) { field.set(obj, value); return; } } catch (NoSuchFieldException e) { LogSupport.ignore(log, e); } // Search for a match by trying all the set methods Method[] sets = oClass.getMethods(); Method set = null; for (int s = 0; sets != null && s < sets.length; s++) { if (name.equals(sets[s].getName()) && sets[s].getParameterTypes().length == 1) { // lets try it try { set = sets[s]; sets[s].invoke(obj, arg); return; } catch (IllegalArgumentException e) { LogSupport.ignore(log, e); } catch (IllegalAccessException e) { LogSupport.ignore(log, e); } } } // Try converting the arg to the last set found. if (set != null) { try { Class sClass = set.getParameterTypes()[0]; if (sClass.isPrimitive()) { for (int t = 0; t < __primitives.length; t++) { if (sClass.equals(__primitives[t])) { sClass = __primitiveHolders[t]; break; } } } Constructor cons = sClass.getConstructor(vClass); arg[0] = cons.newInstance(arg); set.invoke(obj, arg); return; } catch (NoSuchMethodException e) { LogSupport.ignore(log, e); } catch (IllegalAccessException e) { LogSupport.ignore(log, e); } catch (InstantiationException e) { LogSupport.ignore(log, e); } } // No Joy throw new NoSuchMethodException(oClass + "." + name + "(" + vClass[0] + ")"); }
From source file:org.glowroot.agent.weaving.ClassAnalyzer.java
@RequiresNonNull("bridgeTargetAdvisors") private List<Advice> analyzeMethod(ThinMethod thinMethod) { if (Modifier.isFinal(thinMethod.access()) && Modifier.isPublic(thinMethod.access())) { ImmutablePublicFinalMethod.Builder builder = ImmutablePublicFinalMethod.builder() .name(thinMethod.name()); List<Type> parameterTypes = Arrays.asList(Type.getArgumentTypes(thinMethod.descriptor())); for (Type parameterType : parameterTypes) { builder.addParameterTypes(parameterType.getClassName()); }/*from w w w . j a v a 2 s . com*/ analyzedClassBuilder.addPublicFinalMethods(builder.build()); } if (shortCircuitBeforeAnalyzeMethods) { return ImmutableList.of(); } List<Type> parameterTypes = Arrays.asList(Type.getArgumentTypes(thinMethod.descriptor())); Type returnType = Type.getReturnType(thinMethod.descriptor()); List<String> methodAnnotations = thinMethod.annotations(); List<Advice> matchingAdvisors = getMatchingAdvisors(thinMethod, methodAnnotations, parameterTypes, returnType); boolean intfMethod = intf && !Modifier.isStatic(thinMethod.access()); if (matchingAdvisors.isEmpty() && !intfMethod) { return ImmutableList.of(); } ImmutableAnalyzedMethod.Builder builder = ImmutableAnalyzedMethod.builder(); builder.name(thinMethod.name()); for (Type parameterType : parameterTypes) { builder.addParameterTypes(parameterType.getClassName()); } builder.returnType(returnType.getClassName()).modifiers(thinMethod.access()) .signature(thinMethod.signature()); for (String exception : thinMethod.exceptions()) { builder.addExceptions(ClassNames.fromInternalName(exception)); } List<Advice> subTypeRestrictedAdvisors = Lists.newArrayList(); for (Iterator<Advice> i = matchingAdvisors.iterator(); i.hasNext();) { Advice advice = i.next(); if (!isSubTypeRestrictionMatch(advice, superClassNames)) { subTypeRestrictedAdvisors.add(advice); i.remove(); } } builder.addAllAdvisors(matchingAdvisors).addAllSubTypeRestrictedAdvisors(subTypeRestrictedAdvisors); analyzedClassBuilder.addAnalyzedMethods(builder.build()); return matchingAdvisors; }