List of usage examples for java.lang.reflect Field getModifiers
public int getModifiers()
From source file:org.openinfinity.core.aspect.ArgumentBuilder.java
private void doRecursiveFieldLookUpAndCallFieldCallback( final ArgumentGatheringFieldCallback<Field, Object> argumentGatheringCallback, final Object[] objects) { for (final Object object : objects) { try {/*from w w w. ja v a2 s . c o m*/ if (object != null) { ReflectionUtils.doWithFields(object.getClass(), new FieldCallback() { public void doWith(Field field) { try { if (!field.isAccessible()) { field.setAccessible(Boolean.TRUE); } if (!(Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers()))) { argumentGatheringCallback.onField(field, object); LOGGER.debug("Accessing field: " + field.getName()); } } catch (Throwable e) { LOGGER.error("Failure occurred while accessing object field.", e); } } }); } } catch (Throwable throwable) { throw new SystemException(throwable); } } }
From source file:org.kaaproject.kaa.server.verifiers.facebook.verifier.FacebookUserVerifierTest.java
private void setFinalStatic(Field field, Object newValue) throws Exception { field.setAccessible(true);//w w w .j a va2 s . c o m Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(null, newValue); }
From source file:de.micromata.genome.util.bean.PrivateBeanUtils.java
/** * Write final static field.// w ww. j av a 2 s . co m * * @param field the field * @param value the value */ public static void writeFinalStaticField(Field field, Object value) { AccessibleScope ascope = new AccessibleScope(field); try { Field modifiersField = Field.class.getDeclaredField("modifiers"); AccessibleScope modscope = new AccessibleScope(field); try { int oldmods = field.getModifiers(); modifiersField.setInt(field, oldmods & ~Modifier.FINAL); writeField(null, field, value); modifiersField.setInt(field, oldmods); } finally { modscope.restore(); } } catch (RuntimeException ex) { // NOSONAR "Illegal Catch" framework throw ex; // NOSONAR "Illegal Catch" framework } catch (Exception ex) { // NOSONAR "Illegal Catch" framework throw new RuntimeException( "Cannot write field: " + field.getDeclaringClass().getName() + "." + field.getName());// NOSONAR "Illegal Catch" framework } finally { ascope.restore(); } }
From source file:cern.c2mon.shared.common.datatag.address.impl.HardwareAddressImpl.java
@Override public final int hashCode() { int result = 0; Field[] fields = this.getClass().getDeclaredFields(); for (Field field : fields) { // compare non-final, non-static and non-transient fields only if (!Modifier.isFinal(field.getModifiers()) && !Modifier.isStatic(field.getModifiers()) && !Modifier.isTransient(field.getModifiers())) { try { // skip arrays if (!field.getType().isArray() && field.get(this) != null) { // for string take its length if (field.getType().equals(String.class)) { result ^= ((String) field.get(this)).length(); } else if (field.getType().equals(short.class) || field.getType().equals(Short.class)) { result ^= field.getShort(this); } else if (field.getType().equals(int.class) || field.getType().equals(Integer.class)) { result ^= field.getInt(this); } else if (field.getType().equals(float.class) || field.getType().equals(Float.class)) { result ^= (int) field.getFloat(this); } else if (field.getType().equals(double.class) || field.getType().equals(Double.class)) { result ^= (int) field.getDouble(this); } else if (field.getType().equals(long.class) || field.getType().equals(Long.class)) { result ^= (int) field.getLong(this); } else if (field.getType().equals(byte.class) || field.getType().equals(Byte.class)) { result ^= field.getByte(this); } else if (field.getType().equals(boolean.class) || field.getType().equals(Boolean.class)) { result ^= field.getBoolean(this) == Boolean.TRUE ? 1 : 0; }/* w w w . ja v a 2 s . c o m*/ } } catch (Exception e) { log.error(e.toString()); throw new RuntimeException("Exception caught while calculating HardwareAddress hashcode.", e); } } } return result; }
From source file:org.apache.apex.malhar.stream.api.impl.ApexStreamImpl.java
private void checkArguments(Operator op, Operator.InputPort inputPort, Operator.OutputPort outputPort) { if (op == null) { throw new IllegalArgumentException("Operator can not be null"); }/*from w ww . j a v a 2 s . c o m*/ boolean foundInput = inputPort == null; boolean foundOutput = outputPort == null; for (Field f : op.getClass().getFields()) { int modifiers = f.getModifiers(); if (!Modifier.isPublic(modifiers) || !Modifier.isTransient(modifiers)) { continue; } Object obj = null; try { obj = f.get(op); } catch (IllegalAccessException e) { // NonAccessible field is not a valid port object } if (obj == outputPort) { foundOutput = true; } if (obj == inputPort) { foundInput = true; } } if (!foundInput || !foundOutput) { throw new IllegalArgumentException("Input port " + inputPort + " and/or Output port " + outputPort + " is/are not owned by Operator " + op); } }
From source file:code.elix_x.excore.utils.nbt.mbt.encoders.NBTClassEncoder.java
public void populate(MBT mbt, NBTTagCompound nbt, Object o) { Class clazz = o.getClass();/*w ww .j av a2 s . co m*/ try { while (clazz != null && clazz != Object.class) { if (!clazz.isAnnotationPresent(MBTIgnore.class)) { for (Field field : clazz.getDeclaredFields()) { if (!field.isAnnotationPresent(MBTIgnore.class)) { field.setAccessible(true); if (nbt.hasKey(field.getName())) { if (encodeStatic || !Modifier.isStatic(field.getModifiers())) { if (Modifier.isFinal(field.getModifiers())) { if (encodeFinal) { Field modifiers = Field.class.getDeclaredField("modifiers"); modifiers.setAccessible(true); modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL); if (field.getGenericType() instanceof ParameterizedType) { Type[] types = ((ParameterizedType) field.getGenericType()) .getActualTypeArguments(); Class[] clas = new Class[] {}; for (Type type : types) { if (type instanceof Class) { clas = ArrayUtils.add(clas, (Class) type); } } field.set(o, mbt.fromNBT(nbt.getTag(field.getName()), field.getType(), clas)); } else { field.set(o, mbt.fromNBT(nbt.getTag(field.getName()), field.getType())); } } } else { if (field.getGenericType() instanceof ParameterizedType) { Type[] types = ((ParameterizedType) field.getGenericType()) .getActualTypeArguments(); Class[] clas = new Class[] {}; for (Type type : types) { if (type instanceof Class) { clas = ArrayUtils.add(clas, (Class) type); } } field.set(o, mbt.fromNBT(nbt.getTag(field.getName()), field.getType(), clas)); } else { field.set(o, mbt.fromNBT(nbt.getTag(field.getName()), field.getType())); } } } } } } } clazz = encodeSuper ? clazz.getSuperclass() : Object.class; } } catch (IllegalArgumentException e) { Throwables.propagate(e); } catch (IllegalAccessException e) { Throwables.propagate(e); } catch (NoSuchFieldException e) { Throwables.propagate(e); } catch (SecurityException e) { Throwables.propagate(e); } }
From source file:io.mandrel.common.schema.SchemaTest.java
public void inspect(int level, Type clazz, String name) { if (level > 6) return;/*w ww . j av a2s . co m*/ if (clazz instanceof Class && clazz.equals(LinkFilter.class)) return; if (clazz instanceof Class && !((Class<?>) clazz).isEnum() && ((Class<?>) clazz).getPackage() != null && ((Class<?>) clazz).getPackage().getName().startsWith("io.mandrel")) { int newLevel = level + 1; List<Field> fields = new ArrayList<Field>(); Class<?> i = ((Class<?>) clazz); while (i != null && i != Object.class) { fields.addAll(Arrays.asList(i.getDeclaredFields())); i = i.getSuperclass(); } for (Field field : fields) { Class<?> fieldType = field.getType(); String text; if (!field.isAnnotationPresent(JsonIgnore.class) && !Modifier.isStatic(field.getModifiers())) { if (List.class.equals(fieldType) || Map.class.equals(fieldType)) { Type type = field.getGenericType(); if (type instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) type; for (Type paramType : pType.getActualTypeArguments()) { if (paramType instanceof Class && NamedDefinition.class.isAssignableFrom((Class) paramType)) { text = field.getName() + "(container of " + paramType + " oneOf)"; System.err.println( StringUtils.leftPad(text, text.length() + newLevel * 5, "\t- ")); Class<? extends NamedDefinition> nd = (Class<? extends NamedDefinition>) field .getType(); Map<String, ? extends NamedDefinition> map = NamedProviders.get(nd); map.forEach((k, v) -> { String text2 = k; System.err.println(StringUtils.leftPad(text2, text2.length() + newLevel * 5, "\t- ")); inspect(newLevel, v.getClass(), field.getName()); }); } else if (paramType instanceof ParameterizedType && NamedDefinition.class .isAssignableFrom((Class) ((ParameterizedType) paramType).getRawType())) { text = field.getName() + "(container of " + paramType + " oneOf2)"; System.err.println( StringUtils.leftPad(text, text.length() + newLevel * 5, "\t- ")); Class<? extends NamedDefinition> nd = (Class<? extends NamedDefinition>) ((ParameterizedType) paramType) .getRawType(); Map<String, ? extends NamedDefinition> map = NamedProviders.get(nd); map.forEach((k, v) -> { String text2 = k; System.err.println(StringUtils.leftPad(text2, text2.length() + newLevel * 5, "\t- ")); inspect(newLevel, v.getClass(), field.getName()); }); } else if (paramType instanceof WildcardType) { for (Type wildType : ((WildcardType) paramType).getUpperBounds()) { if (wildType instanceof Class && NamedDefinition.class.isAssignableFrom((Class) wildType)) { text = field.getName() + "(container of " + wildType + " oneOf)"; System.err.println(StringUtils.leftPad(text, text.length() + newLevel * 5, "\t- ")); Class<? extends NamedDefinition> nd = (Class<? extends NamedDefinition>) field .getType(); Map<String, ? extends NamedDefinition> map = NamedProviders.get(nd); map.forEach((k, v) -> { String text2 = k; System.err.println(StringUtils.leftPad(text2, text2.length() + newLevel * 5, "\t- ")); inspect(newLevel, v.getClass(), field.getName()); }); } else if (wildType instanceof ParameterizedType && NamedDefinition.class.isAssignableFrom( (Class) ((ParameterizedType) wildType).getRawType())) { text = field.getName() + "(container of " + wildType + " oneOf2)"; System.err.println(StringUtils.leftPad(text, text.length() + newLevel * 5, "\t- ")); Class<? extends NamedDefinition> nd = (Class<? extends NamedDefinition>) ((ParameterizedType) wildType) .getRawType(); Map<String, ? extends NamedDefinition> map = NamedProviders.get(nd); map.forEach((k, v) -> { String text2 = k; System.err.println(StringUtils.leftPad(text2, text2.length() + newLevel * 5, "\t- ")); inspect(newLevel, v.getClass(), field.getName()); }); } } } else { text = field.getName() + "(container of " + paramType + ")"; System.err.println( StringUtils.leftPad(text, text.length() + newLevel * 5, "\t- ")); inspect(newLevel, paramType, ""); } } } } else { if (NamedDefinition.class.isAssignableFrom(field.getType())) { text = field.getName() + " oneOf"; System.err.println(StringUtils.leftPad(text, text.length() + newLevel * 5, "\t- ")); Class<? extends NamedDefinition> nd = (Class<? extends NamedDefinition>) field .getType(); Map<String, ? extends NamedDefinition> map = NamedProviders.get(nd); map.forEach((k, v) -> { String text2 = k; System.err.println( StringUtils.leftPad(text2, text2.length() + newLevel * 5, "\t- ")); inspect(newLevel, v.getClass(), field.getName()); }); } else { text = field.getName() + (field.getType().isPrimitive() || field.getType().equals(String.class) || field.getType().equals(LocalDateTime.class) ? " (" + field.getType().getName() + ")" : ""); System.err.println(StringUtils.leftPad(text, text.length() + newLevel * 5, "\t- ")); inspect(newLevel, fieldType, field.getName()); } } // JsonSubTypes subtype = // fieldType.getAnnotation(JsonSubTypes.class); // if (subtype != null) { // int subLevel = level + 2; // text = "subtypes:"; // System.err.println(StringUtils.leftPad(text, // text.length() + subLevel * 5, "\t- ")); // for (JsonSubTypes.Type type : subtype.value()) { // text = "subtype:" + type.name(); // System.err.println(StringUtils.leftPad(text, // text.length() + (subLevel + 1) * 5, "\t- ")); // inspect((subLevel + 1), type.value(), type.name()); // } // } } } JsonSubTypes subtype = ((Class<?>) clazz).getAnnotation(JsonSubTypes.class); if (subtype != null) { int subLevel = level + 1; String text = "subtypes:"; System.err.println(StringUtils.leftPad(text, text.length() + subLevel * 5, "\t- ")); for (JsonSubTypes.Type type : subtype.value()) { text = "subtype:" + type.name(); System.err.println(StringUtils.leftPad(text, text.length() + (subLevel + 1) * 5, "\t- ")); inspect((subLevel + 1), type.value(), type.name()); } } } }
From source file:com.gwtcx.server.servlet.FileUploadServlet.java
@SuppressWarnings("rawtypes") private Object createEntity(Class entity, Field[] fields, String[] nextLine) { Log.debug("createEntity()"); try {//from w w w . j ava 2 s .co m Object object = entity.newInstance(); for (Field field : fields) { Class type = field.getType(); // ignore Static fields if (Modifier.isStatic(field.getModifiers())) { continue; } if (type.getSimpleName().equals("String")) { Integer index = fieldNames.get(field.getName()); if (index != null) { field.set(object, nextLine[index].trim()); Log.debug("Field name: " + field.getName() + " index[" + index + "] = " + nextLine[index]); } } else if (type.getSimpleName().equals("List")) { List<Object> list = new ArrayList<Object>(); Field declaredField = object.getClass().getDeclaredField(field.getName()); Type genericType = declaredField.getGenericType(); if (genericType instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) genericType; Type[] t = pt.getActualTypeArguments(); // e.g. "class au.com.uptick.serendipity.server.domain.Address" String className = t[0].toString().substring(6); Log.debug("className: " + className); Class nestedEntity = Class.forName(className); Field[] nestedFields = nestedEntity.getDeclaredFields(); AccessibleObject.setAccessible(nestedFields, true); Object nestedObject = createNestedEntity(nestedEntity, nestedFields, nextLine); if (nestedObject != null) { list.add(nestedObject); field.set(object, list); } } } } // Log.debug(object.toString()); return object; } catch (Exception e) { Log.error("Error encountered while creating entity", e); } return null; }
From source file:org.apache.lens.api.jaxb.YAMLToStringStrategy.java
@Override protected StringBuilder appendInternal(ObjectLocator locator, StringBuilder stringBuilder, Object value) { insideArray = insideArrayStack.peek(); insideArrayStack.push(false);/*from w w w. java2 s.c o m*/ try { if (value instanceof String && ((String) value).isEmpty()) { appendNullText(stringBuilder); return stringBuilder; } if (!canBeInlinedWithOtherArrayElements(value)) { appendNewLine(stringBuilder); } if (value instanceof Map) { indentationValue++; for (Object key : ((Map) value).keySet()) { appendNewLine(indent(stringBuilder).append(key).append(": ").append(((Map) value).get(key))); } indentationValue--; return stringBuilder; } if (value instanceof XProperty || value instanceof XPartSpecElement || value instanceof XTimePartSpecElement || value instanceof ResultColumn) { removeLastArrayStart(stringBuilder); if (value instanceof ResultColumn) { ResultColumn column = (ResultColumn) value; indent(stringBuilder).append(column.getName()).append(": ").append(column.getType()); } if (value instanceof XProperty) { XProperty property = (XProperty) value; indent(stringBuilder).append(property.getName()).append(": ").append(property.getValue()); } if (value instanceof XPartSpecElement) { XPartSpecElement partSpecElement = (XPartSpecElement) value; indent(stringBuilder).append(partSpecElement.getKey()).append(": ") .append(partSpecElement.getValue()); } if (value instanceof XTimePartSpecElement) { XTimePartSpecElement partSpecElement = (XTimePartSpecElement) value; indent(stringBuilder).append(partSpecElement.getKey()).append(": ") .append(partSpecElement.getValue()); } return appendNewLine(stringBuilder); } if (value instanceof XJoinEdge) { XJoinEdge edge = (XJoinEdge) value; XTableReference from = edge.getFrom(); XTableReference to = edge.getTo(); stringBuilder.setLength(stringBuilder.length() - 2); stringBuilder.append(from.getTable()).append(".").append(from.getColumn()) .append(from.isMapsToMany() ? "(many)" : "").append("=").append(to.getTable()).append(".") .append(to.getColumn()).append(to.isMapsToMany() ? "(many)" : ""); return appendNewLine(stringBuilder); } NameableContext context = getNameableContext(value); if (context != null) { String heading = context.getHeading(); if (isBlank(heading)) { heading = "-"; } if (insideArray) { stringBuilder.setLength(stringBuilder.length() - 2); } String details = context.getDetails(); stringBuilder.append(heading); if (details.charAt(0) != '\n') { stringBuilder.append(" "); } stringBuilder.append(details); return appendNewLine(stringBuilder); } // some other way of getting heading if (value instanceof Collection) { Collection collection = (Collection) value; // try inline StringBuilder allElements = super.appendInternal(locator, new StringBuilder(), value); if (collection.size() != 0 && canBeInlinedWithOtherArrayElements((collection.iterator().next())) && allElements.length() < 120) { stringBuilder.setLength(stringBuilder.length() - 1); String sep = " "; for (Object singleElement : collection) { stringBuilder.append(sep); appendInternal(locator, stringBuilder, singleElement); sep = ", "; } return stringBuilder; } else { return stringBuilder.append(allElements); } } // If this class is just a wrapper over a another object Field[] fields = value.getClass().getDeclaredFields(); int nonStaticFields = 0; String fieldName = null; for (Field field : fields) { if (!Modifier.isStatic(field.getModifiers())) { nonStaticFields++; fieldName = field.getName(); } } if (nonStaticFields == 1) { Class<?> claz = value.getClass(); String getterName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); try { Object wrappedValue = claz.getDeclaredMethod(getterName).invoke(value); return appendNewLine(appendInternal(locator, stringBuilder, wrappedValue)); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { log.trace("getter access failed for {}#{}. Going the usual way", claz.getName(), getterName, e); } } return super.appendInternal(locator, stringBuilder, value); } finally { insideArrayStack.pop(); } }
From source file:co.cask.cdap.filetailer.FileTailerIT.java
private void mockMetricsProcessor(PipeManager manager) throws IOException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException { List<Pipe> pipeList = new ArrayList<Pipe>(); StreamClient client = null;/*from www.j ava2 s . c om*/ StreamWriter writer = null; try { Method method1 = manager.getClass().getDeclaredMethod("getPipeConfigs"); method1.setAccessible(true); List<PipeConfiguration> pipeConfList = (List<PipeConfiguration>) method1.invoke(manager); for (PipeConfiguration pipeConf : pipeConfList) { FileTailerQueue queue = new FileTailerQueue(pipeConf.getQueueSize()); client = pipeConf.getSinkConfiguration().getStreamClient(); String streamName = pipeConf.getSinkConfiguration().getStreamName(); Method method2 = manager.getClass().getDeclaredMethod("getStreamWriterForPipe", StreamClient.class, String.class); method2.setAccessible(true); writer = (StreamWriter) method2.invoke(manager, client, streamName); FileTailerStateProcessor stateProcessor = new FileTailerStateProcessorImpl(pipeConf.getDaemonDir(), pipeConf.getStateFile()); FileTailerMetricsProcessor metricsProcessor = new FileTailerMetricsProcessor( pipeConf.getDaemonDir(), pipeConf.getStatisticsFile(), pipeConf.getStatisticsSleepInterval(), pipeConf.getPipeName(), pipeConf.getSourceConfiguration().getFileName()) { @Override public void onReadEventMetric(int eventSize) { super.onReadEventMetric(eventSize); read.incrementAndGet(); } @Override public void onIngestEventMetric(int latency) { super.onIngestEventMetric(latency); ingest.incrementAndGet(); } }; pipeList.add(new Pipe(new LogTailer(pipeConf, queue, stateProcessor, metricsProcessor, null), new FileTailerSink(queue, writer, SinkStrategy.LOADBALANCE, stateProcessor, metricsProcessor, null, pipeConf.getSinkConfiguration().getPackSize()), metricsProcessor)); client = null; writer = null; } Field field = manager.getClass().getDeclaredField("serviceManager"); field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(manager, new ServiceManager(pipeList)); } finally { if (client != null) { client.close(); } if (writer != null) { writer.close(); } } }