private List<Field> allFields(final Class<?> c) { List<Field> l = fieldsCache.get(c); if (l == null) { l = new LinkedList<Field>(); final Field[] fields = c.getDeclaredFields(); addAll(l, fields); Class<?> sc = c; while ((sc = sc.getSuperclass()) != Object.class && sc != null) { addAll(l, sc.getDeclaredFields()); } fieldsCache.putIfAbsent(c, l); } return l; }
Field[] keyFields() { Class c = clazz; try { List<Field> fields = new ArrayList<Field>(); while (!c.equals(Object.class)) { for (Field field : c.getDeclaredFields()) { // TODO: add cashe field->isAnnotationPresent if (InternalCache.isEnableAnnotationPresent()) { if (InternalCache.isAnnotationPresent(Id.class, field) || InternalCache.isAnnotationPresent(EmbeddedId.class, field)) { field.setAccessible(true); fields.add(field); } } else { if (field.isAnnotationPresent(Id.class) || field.isAnnotationPresent(EmbeddedId.class)) { field.setAccessible(true); fields.add(field); } } } c = c.getSuperclass(); } final Field[] f = fields.toArray(new Field[fields.size()]); if (f.length == 0) { throw new UnexpectedException("Cannot get the object @Id for an object of type " + clazz); } return f; } catch (Exception e) { throw new UnexpectedException( "Error while determining the object @Id for an object of type " + clazz); } }
private Field[] getAccessibleFields() { if (includePrivate) { try { List<Field> fieldsList = new ArrayList<Field>(); Class<?> currentClass = cl; while (currentClass != null) { // get all declared fields in this class, make them // accessible, and save Field[] declared = currentClass.getDeclaredFields(); for (int i = 0; i < declared.length; i++) { declared[i].setAccessible(true); fieldsList.add(declared[i]); } // walk up superclass chain. no need to deal specially with // interfaces, since they can't have fields currentClass = currentClass.getSuperclass(); } return fieldsList.toArray(new Field[fieldsList.size()]); } catch (SecurityException e) { // fall through to !includePrivate case } } return cl.getFields(); }
protected void _addFields(Map<String, AnnotatedField> fields, Class<?> c) { /* First, a quick test: we only care for regular classes (not * interfaces, primitive types etc), except for Object.class. * A simple check to rule out other cases is to see if there * is a super class or not. */ Class<?> parent = c.getSuperclass(); if (parent != null) { // Let's add super-class' fields first, then ours. /* 21-Feb-2010, tatu: Need to handle masking: as per [JACKSON-226] * we otherwise get into trouble... */ _addFields(fields, parent); for (Field f : c.getDeclaredFields()) { // static fields not included, nor transient if (!_isIncludableField(f)) { continue; } /* Ok now: we can (and need) not filter out ignorable fields * at this point; partly because mix-ins haven't been * added, and partly because logic can be done when * determining get/settability of the field. */ fields.put(f.getName(), _constructField(f)); } // And then... any mix-in overrides? if (_mixInResolver != null) { Class<?> mixin = _mixInResolver.findMixInClassFor(c); if (mixin != null) { _addFieldMixIns(mixin, fields); } } } }
public List<Model.Property> listProperties() { List<Model.Property> properties = new ArrayList<Model.Property>(); Set<Field> fields = new LinkedHashSet<Field>(); Class<?> tclazz = clazz; while (!tclazz.equals(Object.class)) { Collections.addAll(fields, tclazz.getDeclaredFields()); tclazz = tclazz.getSuperclass(); } for (Field f : fields) { int mod = f.getModifiers(); if (Modifier.isTransient(mod) || Modifier.isStatic(mod)) { continue; } if (f.isAnnotationPresent(Transient.class)) { continue; } if (f.isAnnotationPresent(NoBinding.class)) { NoBinding a = f.getAnnotation(NoBinding.class); List<String> values = Arrays.asList(a.value()); if (values.contains("*")) { continue; } } Model.Property mp = buildProperty(f); if (mp != null) { properties.add(mp); } } return properties; }
/** * Returns a map of public static final integer fields in the specified classes, to their String * representations. An optional filter can be specified to only include specific fields. The * target map may be null, in which case a new map is allocated and returned. * * <p>This method is useful when debugging to quickly identify values returned from the AL/GL/CL * APIs. * * @param filter the filter to use (optional) * @param target the target map (optional) * @param tokenClasses the classes to get tokens from * @return the token map */ public static Map<Integer, String> getClassTokens( final TokenFilter filter, Map<Integer, String> target, final Iterable<Class> tokenClasses) { if (target == null) target = new HashMap<Integer, String>(); final int TOKEN_MODIFIERS = Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL; for (final Class tokenClass : tokenClasses) { for (final Field field : tokenClass.getDeclaredFields()) { // Get only <public static final int> fields. if ((field.getModifiers() & TOKEN_MODIFIERS) == TOKEN_MODIFIERS && field.getType() == int.class) { try { final int value = field.getInt(null); if (filter != null && !filter.accept(field, value)) continue; if (target.containsKey(value)) // Print colliding tokens in their hex representation. target.put(value, toHexString(value)); else target.put(value, field.getName()); } catch (IllegalAccessException e) { // Ignore } } } } return target; }
private boolean addClassMemberStaticImports(String packageName) { try { Class c = Class.forName(packageName); initImports(); if (c.isEnum()) { //noinspection unchecked for (Enum e : (EnumSet<?>) EnumSet.allOf(c)) { imports.put(e.name(), e); } return true; } else { for (Field f : c.getDeclaredFields()) { if ((f.getModifiers() & (Modifier.STATIC | Modifier.PUBLIC)) != 0) { imports.put(f.getName(), f.get(null)); } } } } catch (ClassNotFoundException e) { // do nothing. } catch (IllegalAccessException e) { throw new RuntimeException("error adding static imports for: " + packageName, e); } return false; }
private void validateClass(Class<?> source, ValidationProblemCollector problems) { int modifiers = source.getModifiers(); if (Modifier.isInterface(modifiers)) { problems.add("Must be a class, not an interface"); } if (source.getEnclosingClass() != null) { if (Modifier.isStatic(modifiers)) { if (Modifier.isPrivate(modifiers)) { problems.add("Class cannot be private"); } } else { problems.add("Enclosed classes must be static and non private"); } } Constructor<?>[] constructors = source.getDeclaredConstructors(); for (Constructor<?> constructor : constructors) { if (constructor.getParameterTypes().length > 0) { problems.add("Cannot declare a constructor that takes arguments"); break; } } Field[] fields = source.getDeclaredFields(); for (Field field : fields) { int fieldModifiers = field.getModifiers(); if (!field.isSynthetic() && !(Modifier.isStatic(fieldModifiers) && Modifier.isFinal(fieldModifiers))) { problems.add(field, "Fields must be static final."); } } }
private int getNumNonSerialVersionUIDFields(Class clazz) { Field[] declaredFields = clazz.getDeclaredFields(); int numFields = declaredFields.length; List<Field> fieldList = Arrays.asList(declaredFields); // System.out.println(clazz); // // for (Field field : fieldList) { // System.out.println(field.getNode()); // } for (Field field : fieldList) { if (field.getName().equals("serialVersionUID")) { numFields--; } if (field.getName().equals("this$0")) { numFields--; } } // System.out.println(numFields); return numFields; }
public CacheKeyFilter(Class<?> cachedClass) { for (Field field : cachedClass.getDeclaredFields()) { if (field.isAnnotationPresent(CacheKey.class)) { cachedKeys.add(field.getName()); } } }
public static void writeParam(String xNameFile) { // // write to file xpar all parameters..... // IOseq xFile; xFile = new IOseq(xNameFile); xFile.IOseqOpenW(false); try { Class c = Class.forName("jneat.Neat"); Field[] fieldlist = c.getDeclaredFields(); for (int i = 0; i < fieldlist.length; i++) { Field f1 = fieldlist[i]; String x1 = f1.getName(); if (x1.startsWith("p_")) { Field f2 = c.getField("d_" + Neat.normalizeName(x1)); Object s1 = f1.get(c); Object s2 = f2.get(c); // String riga = s1 + " " + s2; String riga = x1 + " " + s1; xFile.IOseqWrite(riga); } } } catch (Throwable e) { System.err.println(e); } xFile.IOseqCloseW(); }
private static Field locateField(Class<?> fromClass, String expectedName, Class<?> type) { Field found = null; // First: let's see if we can find exact match: Field[] fields = fromClass.getDeclaredFields(); for (Field f : fields) { if (expectedName.equals(f.getName()) && f.getType() == type) { found = f; break; } } // And if not, if there is just one field with the type, that field if (found == null) { for (Field f : fields) { if (f.getType() == type) { // If more than one, can't choose if (found != null) return null; found = f; } } } if (found != null) { // it's non-public, need to force accessible try { found.setAccessible(true); } catch (Throwable t) { } } return found; }
private List<Field> orderedInstanceFieldsFrom(Class<?> awaitingInjectionClazz) { List<Field> declaredFields = Arrays.asList(awaitingInjectionClazz.getDeclaredFields()); declaredFields = ListUtil.filter(declaredFields, notFinalOrStatic); Collections.sort(declaredFields, superTypesLast); return declaredFields; }
private static Field[] getAllFields(Class cls) { ArrayList<Field> res = new ArrayList<>(); Class c = cls; while (c != View.class) { assert Utils.check(c != null); res.addAll(Arrays.asList(c.getDeclaredFields())); c = c.getSuperclass(); } return res.toArray(new Field[res.size()]); }
public static boolean readParam(String xNomeFile) { boolean ret = true; String xline; IOseq xFile; StringTokenizer st; String s1; String s2; Object m1; xFile = new IOseq("parameters.ne"); ret = xFile.IOseqOpenR(); if (ret) { try { Class c = Class.forName("jneat.Neat"); Field[] fieldlist = c.getDeclaredFields(); int number_params = fieldlist.length / 2; for (int i = 0; i < number_params; i++) { Field f1 = fieldlist[i]; String x1 = f1.getName(); Object x2 = f1.getType(); xline = xFile.IOseqRead(); st = new StringTokenizer(xline); // skip comment s1 = st.nextToken(); // real value s1 = st.nextToken(); if (x1.startsWith("p_")) { if (x2.toString().equals("double")) { double n1 = Double.parseDouble(s1); f1.set(c, (new Double(n1))); } if (x2.toString().equals("int")) { int n1 = Integer.parseInt(s1); f1.set(c, (new Integer(n1))); } } } } catch (Throwable e) { System.err.println(e); } xFile.IOseqCloseR(); } else System.err.print("\n : error during open " + xNomeFile); return ret; }
public static Set<Field> getModelFields(Class<?> clazz) { Set<Field> fields = new LinkedHashSet<Field>(); Class<?> tclazz = clazz; while (!tclazz.equals(Object.class)) { // Only add fields for mapped types if (tclazz.isAnnotationPresent(Entity.class) || tclazz.isAnnotationPresent(MappedSuperclass.class)) Collections.addAll(fields, tclazz.getDeclaredFields()); tclazz = tclazz.getSuperclass(); } return fields; }
/** * Prints all fields of a class * * @param cl a class */ public static void printFields(Class cl) { Field[] fields = cl.getDeclaredFields(); for (Field f : fields) { Class type = f.getType(); String name = f.getName(); System.out.print(" "); String modifiers = Modifier.toString(f.getModifiers()); if (modifiers.length() > 0) System.out.print(modifiers + " "); System.out.println(type.getName() + " " + name + ";"); } }
private boolean findAllTestedAndInjectableFieldsInTestClassHierarchy( @NotNull Class<?> testClass) { Class<?> classWithFields = testClass; do { Field[] fields = classWithFields.getDeclaredFields(); findTestedAndInjectableFields(fields); classWithFields = classWithFields.getSuperclass(); } while (classWithFields.getClassLoader() != null); return !testedFields.isEmpty(); }
public Map<String, Object> dumpStats() { HashMap<String, Object> map = new HashMap<String, Object>(); for (Class<?> clazz = this.getClass(); clazz != null; clazz = clazz.getSuperclass()) { Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(ManagedAttribute.class) || (field.isAnnotationPresent(Property.class) && field.getAnnotation(Property.class).exposeAsManagedAttribute())) { String attributeName = field.getName(); try { field.setAccessible(true); Object value = field.get(this); map.put(attributeName, value != null ? value.toString() : null); } catch (Exception e) { log.warn("Could not retrieve value of attribute (field) " + attributeName, e); } } } Method[] methods = this.getClass().getMethods(); for (Method method : methods) { if (method.isAnnotationPresent(ManagedAttribute.class) || (method.isAnnotationPresent(Property.class) && method.getAnnotation(Property.class).exposeAsManagedAttribute())) { String method_name = method.getName(); if (method_name.startsWith("is") || method_name.startsWith("get")) { try { Object value = method.invoke(this); String attributeName = Util.methodNameToAttributeName(method_name); map.put(attributeName, value != null ? value.toString() : null); } catch (Exception e) { log.warn("Could not retrieve value of attribute (method) " + method_name, e); } } else if (method_name.startsWith("set")) { String stem = method_name.substring(3); Method getter = ResourceDMBean.findGetter(getClass(), stem); if (getter != null) { try { Object value = getter.invoke(this); String attributeName = Util.methodNameToAttributeName(method_name); map.put(attributeName, value != null ? value.toString() : null); } catch (Exception e) { log.warn("Could not retrieve value of attribute (method) " + method_name, e); } } } } } } return map; }
/** * Obtiene las columnas de la clave primaria de la entidad. * * @param object Entidad de donde se obtendrán las columnas clave * @return Retorna una lista con las columnas de la clave primaria de la entidad */ @SuppressWarnings("unchecked") protected List<String> obtenerId(Object object) { Class<T> classe = (Class<T>) object.getClass(); Field[] fields = classe.getDeclaredFields(); List<String> id = new ArrayList<String>(); for (Field field : fields) { Annotation[] anotaciones = field.getAnnotations(); for (Annotation annotation : anotaciones) { if ("@javax.persistence.Id()".equals(annotation.toString())) { id.add(field.getName()); break; } else if ("@javax.persistence.EmbeddedId()".equals(annotation.toString())) { String fieldName = field.getName(); String methodName = "get" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1); try { Method method = classe.getMethod(methodName, new Class[] {}); Object result = method.invoke(object, new Object[] {}); Class<T> classe1 = (Class<T>) result.getClass(); Field[] fields1 = classe1.getDeclaredFields(); for (Field fieldPK : fields1) { if (!"serialVersionUID".equals(fieldPK.getName())) { id.add(fieldName + "." + fieldPK.getName()); } } } catch (RuntimeException e) { continue; } catch (NoSuchMethodException e) { continue; } catch (IllegalAccessException e) { continue; } catch (InvocationTargetException e) { continue; } } } } return id; }
private static void convertProtocolToAsciidocTable(Properties props, Class<Protocol> clazz) throws Exception { boolean isUnsupported = clazz.isAnnotationPresent(Unsupported.class); if (isUnsupported) return; Map<String, String> nameToDescription = new TreeMap<>(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(Property.class)) { String property = field.getName(); Property annotation = field.getAnnotation(Property.class); String desc = annotation.description(); nameToDescription.put(property, desc); } } // iterate methods Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { if (method.isAnnotationPresent(Property.class)) { Property annotation = method.getAnnotation(Property.class); String desc = annotation.description(); if (desc == null || desc.isEmpty()) desc = "n/a"; String name = annotation.name(); if (name.length() < 1) { name = Util.methodNameToAttributeName(method.getName()); } nameToDescription.put(name, desc); } } // do we have more than one property (superclass Protocol has only one property (stats)) if (nameToDescription.isEmpty()) return; List<String[]> rows = new ArrayList<>(nameToDescription.size() + 1); rows.add(new String[] {"Name", "Description"}); for (Map.Entry<String, String> entry : nameToDescription.entrySet()) rows.add(new String[] {entry.getKey(), entry.getValue()}); String tmp = createAsciidocTable( rows, clazz.getSimpleName(), "[align=\"left\",width=\"90%\",cols=\"2,10\",options=\"header\"]"); props.put(clazz.getSimpleName(), tmp); }
@SuppressWarnings("unchecked") @Test public void FullySerializable() { Set<Class<?>> checked = new HashSet<Class<?>>(); checked.addAll( Arrays.asList( Collection.class, List.class, Set.class, Map.class, Object.class, String.class, Class.class)); Stack<Class<?>> classes = new Stack<Class<?>>(); classes.addAll( Arrays.<Class<?>>asList( NumberPath.class, NumberOperation.class, NumberTemplate.class, BeanPath.class, DefaultQueryMetadata.class)); while (!classes.isEmpty()) { Class<?> clazz = classes.pop(); checked.add(clazz); if (!Serializable.class.isAssignableFrom(clazz) && !clazz.isPrimitive()) { fail(clazz.getName() + " is not serializable"); } for (Field field : clazz.getDeclaredFields()) { if (Modifier.isTransient(field.getModifiers())) { continue; } Set<Class<?>> types = new HashSet<Class<?>>(3); types.add(field.getType()); if (field.getType().getSuperclass() != null) { types.add(field.getType().getSuperclass()); } if (field.getType().getComponentType() != null) { types.add(field.getType().getComponentType()); } if (Collection.class.isAssignableFrom(field.getType())) { types.add(ReflectionUtils.getTypeParameterAsClass(field.getGenericType(), 0)); } else if (Map.class.isAssignableFrom(field.getType())) { types.add(ReflectionUtils.getTypeParameterAsClass(field.getGenericType(), 0)); types.add(ReflectionUtils.getTypeParameterAsClass(field.getGenericType(), 1)); } types.removeAll(checked); classes.addAll(types); } } }
public Document serialize(Object object, Document doc) { Class c = object.getClass(); Integer id = getID(object); map.put(object, id); String mapSize = Integer.toString(map.size()); // creating serialization objects Element objectElement = new Element("object"); objectElement.setAttribute(new Attribute("class", c.getName())); objectElement.setAttribute(new Attribute("id", mapSize)); doc.getRootElement().addContent(objectElement); if (!c.isArray()) // class is not an array { Field[] fields = c.getDeclaredFields(); ArrayList<Element> fieldXML = serializeFields(fields, object, doc); for (int i = 0; i < fieldXML.size(); i++) { objectElement.addContent(fieldXML.get(i)); } } else // class is an array { Object array = object; objectElement.setAttribute(new Attribute("length", Integer.toString(Array.getLength(array)))); if (c.getComponentType().isPrimitive()) // class is array of primitives { for (int i = 0; i < Array.getLength(array); i++) { Element value = new Element("value"); value.setText(Array.get(c, i).toString()); objectElement.addContent(value); } } else // class is array of references { for (int j = 0; j < Array.getLength(array); j++) { Element ref = new Element("reference"); id = getID(Array.get(c, j)); if (id != -1) { ref.setText(Integer.toString(id)); } } for (int k = 0; k < Array.getLength(array); k++) { serialize(Array.get(array, k), doc); } } } if (currentElement == 0) { referenceID = 0; } return doc; }
private void InitFieldCmd(ICmd cmd, Hashtable<FieldCmdKind, Object> fieldsValue) { Class c = cmd.getClass(); // Класс рассматриваемой команды. Field f[]; // Набор полей рассматриваемого класса. while (c != null) { f = c.getDeclaredFields(); for (Field iF : f) { setFieldValue(iF, cmd, fieldsValue); } c = c.getSuperclass(); } }
private Map<String, Field> getFieldMap(Class<?> classOfT) { Map<String, Field> map = new HashMap<>(); for (Field field : classOfT.getDeclaredFields()) { field.setAccessible(true); String name; if (caseSensitiveFieldNames) { name = field.getName(); } else { name = field.getName().toLowerCase(); } map.put(name, field); } return map; }
public static void clearDeclaredFields(Object test, Class aClass) throws IllegalAccessException { if (aClass == null) return; for (final Field field : aClass.getDeclaredFields()) { @NonNls final String name = field.getDeclaringClass().getName(); if (!name.startsWith("junit.framework.") && !name.startsWith("com.intellij.testFramework.")) { final int modifiers = field.getModifiers(); if ((modifiers & Modifier.FINAL) == 0 && (modifiers & Modifier.STATIC) == 0 && !field.getType().isPrimitive()) { field.setAccessible(true); field.set(test, null); } } } }
private void checkString(T instance) { assertThat( instance.toString(), CoreMatchers.startsWith( type.getCanonicalName().substring(type.getPackage().getName().length() + 1) + "{")); assertThat(instance.toString(), endsWith("}")); Class<?> currentType = type; do { for (Field field : type.getDeclaredFields()) { if (!field.isSynthetic() && !Modifier.isStatic(field.getModifiers()) && !ignoredFields.contains(field.getName())) { assertThat(instance.toString(), containsString(field.getName())); } } } while ((currentType = currentType.getSuperclass()) != Object.class); }
private void injectBeansToComponents() { for (Class<?> c : componentsClasses) { try { Object object = c.newInstance(); for (Field f : c.getDeclaredFields()) { if (f.isAnnotationPresent(Inject.class)) { f.setAccessible(true); Class<?> fieldClass = f.getType(); BeanDefinition beanDefinition = findBeenByClass(fieldClass); f.set(object, beanDefinition.getInstance()); } } preparedComponents.put(c.getName(), new SingletonBeanDefinition(c, object)); } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); } } }
/** * Returns the shallow instance size in bytes an instance of the given class would occupy. This * works with all conventional classes and primitive types, but not with arrays (the size then * depends on the number of elements and varies from object to object). * * @see #shallowSizeOf(Object) * @throws IllegalArgumentException if {@code clazz} is an array class. */ public static long shallowSizeOfInstance(Class<?> clazz) { if (clazz.isArray()) throw new IllegalArgumentException("This method does not work with array classes."); if (clazz.isPrimitive()) return primitiveSizes.get(clazz); long size = NUM_BYTES_OBJECT_HEADER; // Walk type hierarchy for (; clazz != null; clazz = clazz.getSuperclass()) { final Field[] fields = clazz.getDeclaredFields(); for (Field f : fields) { if (!Modifier.isStatic(f.getModifiers())) { size = adjustForField(size, f); } } } return alignObjectSize(size); }
/** * Obtiene las propiedades de la entidad a la cual pertenece el DAO. * * @param object entidad a la que pertenece el DAO. * @param clave la entidad embebida que contiene la clave primaria * @return Mapa con las propiedades y los valores, el cual será utilizado para la construcción de * los criterios en la ejecución de la búsqueda. */ @SuppressWarnings("unchecked") private Map<String, Object> obtenerPropiedades(Object object, String... clave) { Class<T> classe = (Class<T>) object.getClass(); Field[] fields = classe.getDeclaredFields(); Map<String, Object> mapa = new HashMap<String, Object>(fields.length); for (Field field : fields) { Boolean isClob = Boolean.FALSE; Annotation[] anotaciones = field.getAnnotations(); for (Annotation annotation : anotaciones) { if ("@javax.persistence.Lob()".equals(annotation.toString()) || "@javax.persistence.Transient()".equals(annotation.toString())) { isClob = Boolean.TRUE; break; } } if (!isClob) { String fieldName = field.getName(); String methodName = "get" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1); try { Method method = classe.getMethod(methodName, new Class[] {}); Object result = method.invoke(object, new Object[] {}); if (result != null) { if (clave != null && clave.length == 1) { mapa.put(clave[0] + "." + field.getName(), result); } else { mapa.put(field.getName(), result); } } } catch (RuntimeException e) { continue; } catch (NoSuchMethodException e) { continue; } catch (IllegalAccessException e) { continue; } catch (InvocationTargetException e) { continue; } } } return mapa; }