List of usage examples for java.lang.reflect Method getName
@Override
public String getName()
From source file:com.codeabovelab.dm.common.utils.PojoBeanUtils.java
/** * Copy properties into lombok-style builders (it builder do not follow java bean convention) * @param src source bean object//from w ww . j ava 2 s .c om * @param dst destination builder object * @return dst object */ public static <T> T copyToBuilder(Object src, T dst) { PojoClass srcpojo = new PojoClass(src.getClass()); Class<?> builderClass = dst.getClass(); Method[] methods = builderClass.getMethods(); for (Method method : methods) { boolean isBuilderSetter = method.getReturnType().equals(builderClass) && method.getParameterCount() == 1; if (!isBuilderSetter) { continue; } String propertyName = method.getName(); Property property = srcpojo.getProperties().get(propertyName); if (property == null) { continue; } Object val = property.get(src); if (val == null) { continue; } try { method.invoke(dst, val); } catch (Exception e) { //nothing } } return dst; }
From source file:com.netflix.astyanax.util.StringUtils.java
public static <T> String joinClassGettersValues(final T object, String name, Class<T> clazz) { Method[] methods = clazz.getDeclaredMethods(); StringBuilder sb = new StringBuilder(); sb.append(name).append("["); sb.append(org.apache.commons.lang.StringUtils.join(Collections2.transform( // Filter any field that does not start with lower case // (we expect constants to start with upper case) Collections2.filter(Arrays.asList(methods), new Predicate<Method>() { @Override//from ww w . ja va 2 s . c o m public boolean apply(Method method) { if ((method.getModifiers() & Modifier.STATIC) == Modifier.STATIC) return false; return org.apache.commons.lang.StringUtils.startsWith(method.getName(), "get"); } }), // Convert field to "name=value". value=*** on error new Function<Method, String>() { @Override public String apply(Method method) { Object value; try { value = method.invoke(object); } catch (Exception e) { value = "***"; } return org.apache.commons.lang.StringUtils.uncapitalize( org.apache.commons.lang.StringUtils.substring(method.getName(), 3)) + "=" + value; } }), ",")); sb.append("]"); return sb.toString(); }
From source file:com.all.shared.util.JsonConverterPrimitiveCompliance.java
private static boolean isSetter(Method method) { if (!method.getName().startsWith("set")) { return false; }//from www . ja v a2 s. com if (method.getParameterTypes().length != 1) { return false; } if (!void.class.equals(method.getReturnType())) { return false; } return true; }
From source file:ca.sqlpower.testutil.TestUtils.java
/** * Returns the set of property names which have both a getter and a setter * method and are annotated to be persisted through the {@link SPPersister} * classes.// w w w. j a v a 2 s .c o m * * @param objectUnderTest * The object that contains the persistable properties we want to * find. * @param includeTransient * If true the properties marked as transient will also be * included. If false only the properties that are persisted and * not transient are returned. * @param includeConstructorMutators * If true the properties that have getters but can only be set * through a constructor due to being final will be included. If * false the persisted properties provided must have a setter. */ public static Set<String> findPersistableBeanProperties(SPObject objectUnderTest, boolean includeTransient, boolean includeConstructorMutators) throws Exception { Set<String> getters = new HashSet<String>(); Set<String> setters = new HashSet<String>(); for (Method m : objectUnderTest.getClass().getMethods()) { if (m.getName().equals("getClass")) continue; //skip non-public methods as they are not visible for persisting anyways. if (!Modifier.isPublic(m.getModifiers())) continue; //skip static methods if (Modifier.isStatic(m.getModifiers())) continue; if (m.getName().startsWith("get") || m.getName().startsWith("is")) { Class<?> parentClass = objectUnderTest.getClass(); boolean accessor = false; boolean ignored = false; boolean isTransient = false; parentClass.getMethod(m.getName(), m.getParameterTypes());//test while (parentClass != null) { Method parentMethod; try { parentMethod = parentClass.getMethod(m.getName(), m.getParameterTypes()); } catch (NoSuchMethodException e) { parentClass = parentClass.getSuperclass(); continue; } if (parentMethod.getAnnotation(Accessor.class) != null) { accessor = true; if (parentMethod.getAnnotation(Transient.class) != null) { isTransient = true; } break; } else if (parentMethod.getAnnotation(NonProperty.class) != null || parentMethod.getAnnotation(NonBound.class) != null) { ignored = true; break; } parentClass = parentClass.getSuperclass(); } if (accessor) { if (includeTransient || !isTransient) { if (m.getName().startsWith("get")) { getters.add(m.getName().substring(3)); } else if (m.getName().startsWith("is")) { getters.add(m.getName().substring(2)); } } } else if (ignored) { //ignored so skip } else { fail("The method " + m.getName() + " of " + objectUnderTest.toString() + " is a getter that is not annotated " + "to be an accessor or transient. The exiting annotations are " + Arrays.toString(m.getAnnotations())); } } else if (m.getName().startsWith("set")) { if (m.getAnnotation(Mutator.class) != null) { if ((includeTransient || m.getAnnotation(Transient.class) == null) && (includeConstructorMutators || !m.getAnnotation(Mutator.class).constructorMutator())) { setters.add(m.getName().substring(3)); } } else if (m.getAnnotation(NonProperty.class) != null || m.getAnnotation(NonBound.class) != null) { //ignored so skip and pass } else { fail("The method " + m.getName() + " is a setter that is not annotated " + "to be a mutator or transient."); } } } Set<String> beanNames = new HashSet<String>(); for (String beanName : getters) { if (setters.contains(beanName)) { String firstLetter = new String(new char[] { beanName.charAt(0) }); beanNames.add(beanName.replaceFirst(firstLetter, firstLetter.toLowerCase())); } } return beanNames; }
From source file:de.pribluda.android.jsonmarshaller.JSONMarshaller.java
/** * recursively marshall to JSON/* w ww .ja v a 2 s . co m*/ * * @param sink * @param object */ static void marshallRecursive(JSONObject sink, Object object) throws JSONException, InvocationTargetException, IllegalAccessException, NoSuchMethodException { // nothing to marshall if (object == null) return; // primitive object is a field and does not interes us here if (object.getClass().isPrimitive()) return; // object not null, and is not primitive - iterate through getters for (Method method : object.getClass().getMethods()) { // our getters are parameterless and start with "get" if ((method.getName().startsWith(GETTER_PREFIX) && method.getName().length() > BEGIN_INDEX || method.getName().startsWith(IS_PREFIX) && method.getName().length() > IS_LENGTH) && (method.getModifiers() & Modifier.PUBLIC) != 0 && method.getParameterTypes().length == 0 && method.getReturnType() != void.class) { // is return value primitive? Class<?> type = method.getReturnType(); if (type.isPrimitive() || String.class.equals(type)) { // it is, marshall it Object val = method.invoke(object); if (val != null) { sink.put(propertize(method.getName()), val); } continue; } else if (type.isArray()) { Object val = marshallArray(method.invoke(object)); if (val != null) { sink.put(propertize(method.getName()), val); } continue; } else if (type.isAssignableFrom(Date.class)) { Date date = (Date) method.invoke(object); if (date != null) { sink.put(propertize(method.getName()), date.getTime()); } continue; } else if (type.isAssignableFrom(Boolean.class)) { Boolean b = (Boolean) method.invoke(object); if (b != null) { sink.put(propertize(method.getName()), b.booleanValue()); } continue; } else if (type.isAssignableFrom(Integer.class)) { Integer i = (Integer) method.invoke(object); if (i != null) { sink.put(propertize(method.getName()), i.intValue()); } continue; } else if (type.isAssignableFrom(Long.class)) { Long l = (Long) method.invoke(object); if (l != null) { sink.put(propertize(method.getName()), l.longValue()); } continue; } else { // does it have default constructor? try { if (method.getReturnType().getConstructor() != null) { Object val = marshall(method.invoke(object)); if (val != null) { sink.put(propertize(method.getName()), val); } continue; } } catch (NoSuchMethodException ex) { // just ignore it here, it means no such constructor was found } } } } }
From source file:net.sf.ehcache.config.BeanHandler.java
/** * Finds a creator method.//from w ww .j a v a 2s . c o m */ private static Method findCreateMethod(Class objClass, String name) { final String methodName = makeMethodName("create", name); final Method[] methods = objClass.getMethods(); for (int i = 0; i < methods.length; i++) { final Method method = methods[i]; if (!method.getName().equals(methodName)) { continue; } if (Modifier.isStatic(method.getModifiers())) { continue; } if (method.getParameterTypes().length != 0) { continue; } if (method.getReturnType().isPrimitive() || method.getReturnType().isArray()) { continue; } return method; } return null; }
From source file:com.github.juanmf.java2plant.Parser.java
protected static void addMethodUse(Set<Relation> relations, Class<?> fromType, Type fromParameterType, Method m) { String name = TypesHelper.getSimpleName(m.getName()) + "()"; addUse(relations, fromType, fromParameterType, m, name); }
From source file:com.github.yongchristophertang.engine.java.LoggerProxyHelper.java
static Object addLogger(Logger logger, Method method, Object[] args, Object client) throws Throwable { if (method.getDeclaringClass() == Object.class) { return method.invoke(client, args); }/* ww w . j a v a 2s.c o m*/ String formatter = "\n\tAPI: " + method.getName() + "\n\n"; formatter += "\tInput:\n"; for (int i = 0; i < method.getParameterCount(); i++) { formatter += "\t\t" + method.getParameters()[i].getName() + " (" + method.getParameters()[i].getType().getSimpleName() + "): "; if (args[i] == null) { formatter += "NULL"; } else if (args[i] instanceof Iterable) { int cnt = 0; Iterator iter = ((Iterable) args[i]).iterator(); while (iter.hasNext()) { formatter += "\n\t\t\t[" + (++cnt) + "]: " + toPrinterString(iter.next(), false); } } else { formatter += toPrinterString(args[i], false); } formatter += "\n"; } long bf = System.nanoTime(); Object result; try { result = method.invoke(client, args); } catch (InvocationTargetException e) { formatter += "\n\tException: \n\t\t" + e.getTargetException(); formatter += "\n=======================================================================\n"; logger.info(formatter); throw e.getTargetException(); } long af = System.nanoTime(); formatter += "\n\tResponse Time(ms): " + (af - bf) / 1000000 + "\n\n\tOutput:\n"; if (result == null) { formatter += "\t\tNULL\n"; } else if (result instanceof Iterable) { Iterator iter = ((Iterable) result).iterator(); int cnt = 0; while (iter.hasNext()) { formatter += "\t\t[" + (++cnt) + "]: " + toPrinterString(iter.next(), true) + "\n"; } if (cnt == 0) { formatter += "\t\tEmpty Collection []\n"; } } else { formatter += "\t\t" + toPrinterString(result, true) + "\n"; } formatter += "=======================================================================\n"; logger.info(formatter); return result; }
From source file:Main.java
/** * get the method start with 'get' or 'is'. */// ww w .ja va 2 s. co m public static Method getGetter(Object bean, String property) { Map<String, Method> cache = GETTER_CACHE.get(bean.getClass()); if (cache == null) { cache = new ConcurrentHashMap<>(); for (Method method : bean.getClass().getMethods()) { if (Modifier.isPublic(method.getModifiers()) && !Modifier.isStatic(method.getModifiers()) && !void.class.equals(method.getReturnType()) && method.getParameterTypes().length == 0) { String name = method.getName(); if (name.length() > 3 && name.startsWith("get")) { cache.put(name.substring(3, 4).toLowerCase() + name.substring(4), method); } else if (name.length() > 2 && name.startsWith("is")) { cache.put(name.substring(2, 3).toLowerCase() + name.substring(3), method); } } } Map<String, Method> old = GETTER_CACHE.putIfAbsent(bean.getClass(), cache); if (old != null) { cache = old; } } return cache.get(property); }
From source file:net.servicefixture.util.ReflectionUtils.java
/** * Returns the first public method that matches method name. *///from w w w. ja v a 2s. co m public static Method findMethodByName(Class type, String methodName) { Method[] methods = type.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (method.getName().equals(methodName) && Modifier.isPublic(method.getModifiers())) { return method; } } return null; }