List of usage examples for java.lang.reflect Modifier isStatic
public static boolean isStatic(int mod)
From source file:org.alex73.skarynka.scan.Book2.java
private void get(Object obj, String prefix, List<String> lines) throws Exception { for (Field f : obj.getClass().getFields()) { if (Modifier.isPublic(f.getModifiers()) && !Modifier.isStatic(f.getModifiers()) && !Modifier.isTransient(f.getModifiers())) { if (f.getType() == int.class) { int v = f.getInt(obj); if (v != -1) { lines.add(prefix + f.getName() + "=" + v); }/*from ww w . jav a 2 s. co m*/ } else if (f.getType() == boolean.class) { lines.add(prefix + f.getName() + "=" + f.getBoolean(obj)); } else if (f.getType() == String.class) { String s = (String) f.get(obj); if (s != null) { lines.add(prefix + f.getName() + "=" + s); } } else if (Set.class.isAssignableFrom(f.getType())) { Set<?> set = (Set<?>) f.get(obj); StringBuilder t = new StringBuilder(); for (Object o : set) { t.append(o.toString()).append(';'); } if (t.length() > 0) { t.setLength(t.length() - 1); } lines.add(prefix + f.getName() + "=" + t); } else { throw new RuntimeException("Unknown field class for get '" + f.getName() + "'"); } } } }
From source file:org.apache.cocoon.forms.datatype.EnumSelectionList.java
public void generateSaxFragment(ContentHandler contentHandler, Locale locale) throws SAXException { try {//from ww w. java 2 s . co m contentHandler.startElement(FormsConstants.INSTANCE_NS, SELECTION_LIST_EL, FormsConstants.INSTANCE_PREFIX_COLON + SELECTION_LIST_EL, XMLUtils.EMPTY_ATTRIBUTES); // Create void element if (nullable) { AttributesImpl voidAttrs = new AttributesImpl(); voidAttrs.addCDATAAttribute("value", ""); contentHandler.startElement(FormsConstants.INSTANCE_NS, ITEM_EL, FormsConstants.INSTANCE_PREFIX_COLON + ITEM_EL, voidAttrs); if (this.nullText != null) { contentHandler.startElement(FormsConstants.INSTANCE_NS, LABEL_EL, FormsConstants.INSTANCE_PREFIX_COLON + LABEL_EL, XMLUtils.EMPTY_ATTRIBUTES); contentHandler.startElement(FormsConstants.I18N_NS, TEXT_EL, FormsConstants.I18N_PREFIX_COLON + TEXT_EL, XMLUtils.EMPTY_ATTRIBUTES); contentHandler.characters(nullText.toCharArray(), 0, nullText.length()); contentHandler.endElement(FormsConstants.I18N_NS, TEXT_EL, FormsConstants.I18N_PREFIX_COLON + TEXT_EL); contentHandler.endElement(FormsConstants.INSTANCE_NS, LABEL_EL, FormsConstants.INSTANCE_PREFIX_COLON + LABEL_EL); } contentHandler.endElement(FormsConstants.INSTANCE_NS, ITEM_EL, FormsConstants.INSTANCE_PREFIX_COLON + ITEM_EL); } // Test if we have an apache enum class boolean apacheEnumDone = false; if (Enum.class.isAssignableFrom(clazz)) { Iterator iter = EnumUtils.iterator(clazz); if (iter != null) { apacheEnumDone = true; while (iter.hasNext()) { Enum element = (Enum) iter.next(); String stringValue = clazz.getName() + "." + element.getName(); generateItem(contentHandler, stringValue); } } } // If it's not an apache enum or we didn't manage to read the enum list, then proceed with common method. if (!apacheEnumDone) { Field fields[] = clazz.getDeclaredFields(); for (int i = 0; i < fields.length; ++i) { int mods = fields[i].getModifiers(); if (Modifier.isPublic(mods) && Modifier.isStatic(mods) && Modifier.isFinal(mods) && fields[i].get(null).getClass().equals(clazz)) { String stringValue = clazz.getName() + "." + fields[i].getName(); generateItem(contentHandler, stringValue); } } } // End the selection-list contentHandler.endElement(FormsConstants.INSTANCE_NS, SELECTION_LIST_EL, FormsConstants.INSTANCE_PREFIX_COLON + SELECTION_LIST_EL); } catch (Exception e) { throw new SAXException("Got exception trying to get enum's values", e); } }
From source file:com.holonplatform.core.internal.property.DefaultPropertySetRefIntrospector.java
@Override public PropertySet<?> getPropertySet(PropertySetRef annotation) throws PropertySetIntrospectionException { ObjectUtils.argumentNotNull(annotation, "PropertySetRef annotation must be not null"); // reference class final Class<?> cls = annotation.value(); if (cls == null) { throw new PropertySetIntrospectionException("[PropertySetRef] missing value"); }/*w ww. j a v a 2s . c o m*/ // field name String fieldName = AnnotationUtils.getStringValue(annotation.field()); boolean wasNullFieldName = (fieldName == null); if (fieldName == null) { // check cache synchronized (cache) { final CacheKey key = new CacheKey(cls, null); if (cache.containsKey(key)) { return cache.get(key); } } if (PropertySet.class == cls) { throw new PropertySetIntrospectionException( "Invalid PropertySetRef class value: [" + cls.getName() + "]"); } // If the class itself is a PropertySet, try to instantiate it if (PropertySet.class.isAssignableFrom(cls)) { try { return (PropertySet<?>) cls.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new PropertySetIntrospectionException( "[PropertySetRef] Failed to instantiate PropertySet class [" + cls.getName() + "]", e); } } // Look for a public static PropertySet type field List<String> candidateFieldNames = new LinkedList<>(); Field[] flds = cls.getDeclaredFields(); if (flds != null) { for (Field fld : flds) { if (Modifier.isStatic(fld.getModifiers()) && Modifier.isPublic(fld.getModifiers()) && PropertySet.class.isAssignableFrom(fld.getType())) { candidateFieldNames.add(fld.getName()); } } } if (candidateFieldNames.isEmpty()) { throw new PropertySetIntrospectionException( "[PropertySetRef] Cannot find any valid public static PropertySet type field in class [" + cls.getName() + "]"); } if (candidateFieldNames.size() > 1) { throw new PropertySetIntrospectionException( "[PropertySetRef] More than one valid PropertySet type field found in class [" + cls.getName() + "]: please specify the field name to use in PropertySetRef annotation. Detected PropertySet fields: [" + candidateFieldNames + "]"); } fieldName = candidateFieldNames.get(0); } else { // check cache synchronized (cache) { final CacheKey key = new CacheKey(cls, fieldName); if (cache.containsKey(key)) { return cache.get(key); } } } if (LOGGER.isEnabled(Level.DEBUG)) { final String fn = fieldName; LOGGER.debug(() -> "Get PropertySet using PropertySetRef annotation for class [" + cls + "] and field name [" + fn + "]"); } // Read the PropertySet field try { Object value = FieldUtils.readStaticField(cls, fieldName); if (value == null) { throw new PropertySetIntrospectionException("[PropertySetRef] The field [" + fieldName + "] in class [" + cls.getName() + "] has null value"); } if (!PropertySet.class.isAssignableFrom(value.getClass())) { throw new PropertySetIntrospectionException( "[PropertySetRef] The field [" + fieldName + "] in class [" + cls.getName() + "] is not of PropertySet type but [" + value.getClass().getName() + "]"); } final PropertySet<?> propertySet = (PropertySet<?>) value; // put in cache and return if (wasNullFieldName) { cache.putIfAbsent(new CacheKey(cls, null), propertySet); } PropertySet<?> existing = cache.putIfAbsent(new CacheKey(cls, fieldName), propertySet); return (existing != null ? existing : propertySet); } catch (IllegalAccessException e) { throw new PropertySetIntrospectionException( "[PropertySetRef] Failed to read field [" + fieldName + "] from class [" + cls.getName() + "]", e); } }
From source file:microsoft.exchange.webservices.data.core.service.schema.ServiceObjectSchema.java
/** * Adds schema property to dictionary.//w ww .j a v a2 s .c o m * * @param type Schema type. * @param propDefDictionary The property definition dictionary. */ protected static void addSchemaPropertiesToDictionary(Class<?> type, Map<String, PropertyDefinitionBase> propDefDictionary) { Field[] fields = type.getDeclaredFields(); for (Field field : fields) { int modifier = field.getModifiers(); if (Modifier.isPublic(modifier) && Modifier.isStatic(modifier)) { Object o; try { o = field.get(null); if (o instanceof PropertyDefinition) { PropertyDefinition propertyDefinition = (PropertyDefinition) o; // Some property definitions descend from // ServiceObjectPropertyDefinition but don't have // a Uri, like ExtendedProperties. Ignore them. if (null != propertyDefinition.getUri() && !propertyDefinition.getUri().isEmpty()) { PropertyDefinitionBase existingPropertyDefinition; if (propDefDictionary.containsKey(propertyDefinition.getUri())) { existingPropertyDefinition = propDefDictionary.get(propertyDefinition.getUri()); EwsUtilities.ewsAssert(existingPropertyDefinition == propertyDefinition, "Schema.allSchemaProperties." + "delegate", String.format( "There are at least " + "two distinct property " + "definitions with the" + " following URI: %s", propertyDefinition.getUri())); } else { propDefDictionary.put(propertyDefinition.getUri(), propertyDefinition); // The following is a "generic hack" to register // property that are not public and // thus not returned by the above GetFields // call. It is currently solely used to register // the MeetingTimeZone property. List<PropertyDefinition> associatedInternalProperties = propertyDefinition .getAssociatedInternalProperties(); for (PropertyDefinition associatedInternalProperty : associatedInternalProperties) { propDefDictionary.put(associatedInternalProperty.getUri(), associatedInternalProperty); } } } } } catch (IllegalArgumentException e) { LOG.error(e); // Skip the field } catch (IllegalAccessException e) { LOG.error(e); // Skip the field } } } }
From source file:org.apache.brooklyn.util.javalang.MethodAccessibleReflections.java
private static Maybe<Method> tryFindAccessibleMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) { if (!isAccessible(clazz)) { return Maybe.absent(); }//from ww w . j a v a2s .co m try { Method altMethod = clazz.getMethod(methodName, parameterTypes); if (isAccessible(altMethod) && !Modifier.isStatic(altMethod.getModifiers())) { return Maybe.of(altMethod); } } catch (NoSuchMethodException | SecurityException e) { // Not found; swallow, and return absent } return Maybe.absent(); }
From source file:net.yasion.common.core.bean.wrapper.ExtendedBeanInfo.java
public static boolean isCandidateWriteMethod(Method method) { String methodName = method.getName(); Class<?>[] parameterTypes = method.getParameterTypes(); int nParams = parameterTypes.length; return (methodName.length() > 3 && methodName.startsWith("set") && Modifier.isPublic(method.getModifiers()) && (!void.class.isAssignableFrom(method.getReturnType()) || Modifier.isStatic(method.getModifiers())) && (nParams == 1 || (nParams == 2 && parameterTypes[0].equals(int.class)))); }
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./*ww w .j a v a 2 s . co 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:cz.cuni.mff.d3s.tools.perfdoc.server.measuring.codegen.CodeGenerator.java
private void makeAndCompileMethodCode(BenchmarkSetting setting) throws CompileException, IOException { MethodReflectionInfo mrInfo = (MethodReflectionInfo) setting.getTestedMethod(); Method testedMethod = mrInfo.getMethod(); VelocityContext context = new VelocityContext(); context.put("mFunction", testedMethod); context.put("mFunctionIsStatic", Modifier.isStatic(testedMethod.getModifiers())); context.put("mClass", mrInfo.getContainingClass().getName()); context.put("mFunctionIsNotVoid", !(testedMethod.getReturnType().equals(Void.TYPE))); writeCode(context, templateMethodName); String javaSourceName = javaDestinationDir + directoryName + "/" + templateMethodName + ".java"; String javaClassDirectory = compiledClassDestinationDir + directoryName; List<String> classPaths = getCompilationClassPaths(); classPaths.add(javaClassDirectory);/*from ww w . j av a 2 s . c o m*/ Compiler.compile(javaSourceName, classPaths); }
From source file:com.yahoo.elide.core.EntityBinding.java
/** * Bind fields of an entity including the Id field, attributes, and relationships. * * @param cls Class type to bind fields/*from w ww . jav a 2 s. co m*/ * @param type JSON API type identifier * @param fieldOrMethodList List of fields and methods on entity */ private void bindEntityFields(Class<?> cls, String type, Collection<AccessibleObject> fieldOrMethodList) { for (AccessibleObject fieldOrMethod : fieldOrMethodList) { bindTrigger(OnCreate.class, fieldOrMethod); bindTrigger(OnDelete.class, fieldOrMethod); bindTrigger(OnUpdate.class, fieldOrMethod); bindTrigger(OnCommit.class, fieldOrMethod); if (fieldOrMethod.isAnnotationPresent(Id.class)) { bindEntityId(cls, type, fieldOrMethod); } else if (fieldOrMethod.isAnnotationPresent(Transient.class) && !fieldOrMethod.isAnnotationPresent(ComputedAttribute.class)) { continue; // Transient. Don't serialize } else if (!fieldOrMethod.isAnnotationPresent(Exclude.class)) { if (fieldOrMethod instanceof Field && Modifier.isTransient(((Field) fieldOrMethod).getModifiers())) { continue; // Transient. Don't serialize } if (fieldOrMethod instanceof Method && Modifier.isTransient(((Method) fieldOrMethod).getModifiers())) { continue; // Transient. Don't serialize } if (fieldOrMethod instanceof Field && !fieldOrMethod.isAnnotationPresent(Column.class) && Modifier.isStatic(((Field) fieldOrMethod).getModifiers())) { continue; // Field must have Column annotation? } bindAttrOrRelation(cls, fieldOrMethod); } } }
From source file:com.netflix.bdp.inviso.history.TraceJobHistoryLoader.java
private void handleTaskEvent(HistoryEvent event) throws IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { Task task = new Task(); for (Field f : event.getDatum().getClass().getFields()) { f.setAccessible(true);/*from www.ja v a 2 s. c o m*/ if (Modifier.isStatic(f.getModifiers())) { continue; } String name = f.getName(); Object value = f.get(event.getDatum()); if (skipElements.contains(name)) { continue; } if (value instanceof CharSequence) { value = value.toString(); } if (value == null || value.toString().trim().isEmpty()) { continue; } if ("counters".equals(name)) { Method m = event.getClass().getDeclaredMethod("getCounters", new Class[0]); m.setAccessible(true); Counters counters = (Counters) m.invoke(event, new Object[0]); value = handleCounterEntries(counters); } task.put(name, value); } String taskId = (String) task.get("taskid"); job.getTask(taskId).merge(task); }