List of usage examples for java.lang.reflect Field isAccessible
@Deprecated(since = "9") public boolean isAccessible()
From source file:com.clarkparsia.empire.annotation.RdfGenerator.java
/** * Given an object, return it's rdf:ID. If it already has an id, that will be returned, otherwise the id * will either be generated from the data, using the {@link RdfId} annotation as a guide, or it will auto-generate one. * @param theObj the object/* w w w . j a v a2 s . c om*/ * @return the object's rdf:Id * @throws InvalidRdfException thrown if the object does not support the minimum to create or retrieve an rdf:ID * @see SupportsRdfId */ public static Resource id(Object theObj) throws InvalidRdfException { SupportsRdfId aSupport = asSupportsRdfId(theObj); if (aSupport.getRdfId() != null) { return EmpireUtil.asResource(aSupport); } Field aIdField = BeanReflectUtil.getIdField(theObj.getClass()); String aValue = hash(Strings2.getRandomString(10)); String aNS = RdfId.DEFAULT; URI aURI = FACTORY.createURI(aNS + aValue); if (aIdField != null && !aIdField.getAnnotation(RdfId.class).namespace().equals("")) { aNS = aIdField.getAnnotation(RdfId.class).namespace(); } if (aIdField != null) { boolean aOldAccess = aIdField.isAccessible(); aIdField.setAccessible(true); try { if (aIdField.get(theObj) == null) { throw new InvalidRdfException("id field must have a value"); } Object aValObj = aIdField.get(theObj); aValue = Strings2.urlEncode(aValObj.toString()); if (aValObj instanceof java.net.URI || NetUtils.isURI(aValObj.toString())) { try { aURI = FACTORY.createURI(aValObj.toString()); } catch (IllegalArgumentException e) { // sometimes sesame disagrees w/ Java about what a valid URI is. so we'll have to try // and construct a URI from the possible fragment aURI = FACTORY.createURI(aNS + aValue); } } else { //aValue = hash(aValObj); aURI = FACTORY.createURI(aNS + aValue); } } catch (IllegalAccessException ex) { throw new InvalidRdfException(ex); } aIdField.setAccessible(aOldAccess); } aSupport.setRdfId(new SupportsRdfId.URIKey(java.net.URI.create(aURI.toString()))); return aURI; }
From source file:fi.kela.kanta.util.GenericToString.java
/** * Geneerinen toString metodi, jolla saadaan yksinkertainen siisti key=value listaus annetun luokan attribuuteista. * * @param obj/*from w w w .j a v a2 s . co m*/ * Objekti jonka tiedot halutaan tulostaa. * @return Listaus annetun objektin attribuuteista ja niiden arvoista. */ public String toString(Object obj) { StringBuilder sb = new StringBuilder(); sb.append(obj.getClass().getSimpleName()); sb.append(GenericToString.open_parameters); boolean fieldsAdded = false; for (Field field : GenericToString.getAllFields(obj.getClass())) { // Ei nytet staattisia kentti if (field != null && !java.lang.reflect.Modifier.isStatic(field.getModifiers()) && !(field.getName().startsWith("this$") || field.getName().startsWith("_persistence"))) { fieldsAdded = true; sb.append(field.getName()).append(GenericToString.equals); try { if (field.getType().isPrimitive() || field.getType().isAssignableFrom(String.class)) { if (field.getAnnotation(OmitFromToString.class) != null) { sb.append(hidden_value); } else { sb.append(FieldUtils.readField(obj, field.getName(), true)); } } else if (field.getType().isArray()) { if (!field.isAccessible()) { field.setAccessible(true); } // TODO: Voi jatkokehitt siten ett tulostaa siististi arrayn Object fieldValue = field.get(obj); if (fieldValue != null) { sb.append(GenericToString.na_array); } else { sb.append(GenericToString.null_array); } } else { addObjectInfo(sb, field, obj); } } catch (IllegalAccessException e) { LOGGER.error(e); sb.append(GenericToString.na_access); } sb.append(GenericToString.comma); } } if (fieldsAdded) { // remove last comma and space sb.delete(sb.length() - 2, sb.length()); } sb.append(GenericToString.close_parameters); return sb.toString(); }
From source file:org.openmrs.ObsTest.java
private void setFieldValue(Obs obs, Field field, boolean setAlternateValue) throws Exception { final boolean accessible = field.isAccessible(); if (!accessible) { field.setAccessible(true);/* w ww . j av a2s.c o m*/ } try { Object oldFieldValue = field.get(obs); Object newFieldValue = generateValue(field, setAlternateValue); //sanity check if (setAlternateValue) { assertNotEquals("The old and new values should be different for field: Obs." + field.getName(), oldFieldValue, newFieldValue); } field.set(obs, newFieldValue); } finally { field.setAccessible(accessible); } }
From source file:io.smartspaces.activity.annotation.StandardConfigurationPropertyAnnotationProcessor.java
/** * Injects config parameters into a given field of a given object, if the * field is marked with/* w w w. j a v a 2 s. c o m*/ * {@link io.smartspaces.activity.annotation.ConfigurationProperty}. * * @param obj * object that contains the field into which config parameters will * be injected * @param field * field into which a config parameter will be injected * @param errors * list container to accumulate errors * @param successes * list container to accumulate successes */ private void processField(Object obj, Field field, List<String> errors, List<String> successes) { ConfigurationProperty annotation = field.getAnnotation(ConfigurationProperty.class); if (annotation == null) { return; } int initialErrorSize = errors.size(); String fieldName = field.getName(); if (Modifier.isFinal(field.getModifiers())) { errors.add(String.format("Field '%s' is marked final and may have unpredictable effects", fieldName)); } String property = annotation.name(); if (property == null || property.isEmpty()) { property = annotation.value(); } property = property.trim(); if (property.isEmpty()) { errors.add(String.format("Field '%s' has property name that is all white space or empty", fieldName)); } boolean required = annotation.required(); String delimiter = annotation.delimiter(); boolean accessible = field.isAccessible(); if (!accessible) { field.setAccessible(true); } try { Object value = null; Class<?> type = field.getType(); if (required) { Object defaultValue = field.get(obj); boolean valueIsNotDefault = !Objects.equal(defaultValue, Defaults.defaultValue(type)); if (valueIsNotDefault) { errors.add(String.format( "Field '%s' into which a required property '%s' " + "is to be injected already has a value: '%s', set 'required = false', " + "or set the value of the property in the configuration " + "(do not initialize the field directly).", fieldName, property, defaultValue)); } if (!configuration.containsProperty(property) && !property.isEmpty()) { errors.add(String.format("Field '%s' does not contain required property '%s'", fieldName, property)); } } // If value is required but not present, an error has already been // registered. if (type == int.class || type == Integer.class) { value = configuration.getPropertyInteger(property, null); } else if (type == long.class || type == Long.class) { value = configuration.getPropertyLong(property, null); } else if (type == double.class || type == Double.class) { value = configuration.getPropertyDouble(property, null); } else if (type == boolean.class || type == Boolean.class) { value = configuration.getPropertyBoolean(property, null); } else if (type == String.class) { value = configuration.getPropertyString(property); } else if (type.isAssignableFrom(List.class)) { value = configuration.getPropertyStringList(property, delimiter); } else if (type.isAssignableFrom(Set.class)) { value = configuration.getPropertyStringSet(property, delimiter); } else { errors.add(String.format(String.format("Field '%s' has unsupported type '%s'", fieldName, tryGetValueForErrorMessage(property)))); } if (errors.size() != initialErrorSize) { return; } String header = "@" + ConfigurationProperty.class.getSimpleName(); if (value != null) { successes.add(String.format("%s field '%s' injected property '%s' with value '%s'", header, fieldName, property, value)); field.set(obj, value); } else { successes.add(String.format("%s field '%s' has no value from property '%s', skipping", header, fieldName, property)); } } catch (IllegalAccessException e) { errors.add(String.format("Field '%s' can not be accessed: %s", fieldName, e.toString())); } catch (Exception e) { errors.add(String.format("Field '%s' with property '%s' encountered error: %s", fieldName, tryGetValueForErrorMessage(property), e.toString())); } finally { if (!accessible) { field.setAccessible(false); } } }
From source file:org.apache.nifi.registry.security.authorization.AuthorizerFactory.java
private void performFieldInjection(final Object instance, final Class authorizerClass) throws IllegalArgumentException, IllegalAccessException { for (final Field field : authorizerClass.getDeclaredFields()) { if (field.isAnnotationPresent(AuthorizerContext.class)) { // make the method accessible final boolean isAccessible = field.isAccessible(); field.setAccessible(true);//from w w w . j a v a 2s . c o m try { // get the type final Class<?> fieldType = field.getType(); // only consider this field if it isn't set yet if (field.get(instance) == null) { // look for well known types if (NiFiRegistryProperties.class.isAssignableFrom(fieldType)) { // nifi properties injection field.set(instance, properties); } } } finally { field.setAccessible(isAccessible); } } } final Class parentClass = authorizerClass.getSuperclass(); if (parentClass != null && Authorizer.class.isAssignableFrom(parentClass)) { performFieldInjection(instance, parentClass); } }
From source file:net.minder.config.impl.DefaultConfigurationInjector.java
private void injectFieldValue(Field field, Object target, ConfigurationAdapter adapter, ConfigurationBinding binding) throws ConfigurationException { Configure annotation = field.getAnnotation(Configure.class); if (annotation != null) { Alias alias = field.getAnnotation(Alias.class); String name = getConfigName(field, alias); String bind = getBindName(target, name, binding); Object value = retrieveValue(target, bind, name, field.getType(), adapter, binding); if (value == null) { Optional optional = field.getAnnotation(Optional.class); if (optional == null) { throw new ConfigurationException( String.format("Failed to find configuration for %s bound to %s of %s via %s", bind, name, target.getClass().getName(), adapter.getClass().getName())); }//from w w w . j a v a2 s . c o m } else { try { if (!field.isAccessible()) { field.setAccessible(true); } field.set(target, value); } catch (Exception e) { throw new ConfigurationException( String.format("Failed to inject field configuration property %s of %s", name, target.getClass().getName()), e); } } } }
From source file:org.apache.sling.models.impl.ModelAdapterFactory.java
private RuntimeException setField(InjectableField injectableField, Object createdObject, Object value) { Field field = injectableField.getField(); Result<Object> result = adaptIfNecessary(value, field.getType(), field.getGenericType()); if (result.wasSuccessful()) { boolean accessible = field.isAccessible(); try {//from ww w . j a v a2 s . c o m if (!accessible) { field.setAccessible(true); } field.set(createdObject, result.getValue()); } catch (Exception e) { return new ModelClassException("Could not inject field due to reflection issues", e); } finally { if (!accessible) { field.setAccessible(false); } } return null; } else { return result.getThrowable(); } }
From source file:org.apache.batchee.csv.mapper.DefaultMapper.java
protected DefaultMapper(final Class<T> type, final CoercingConverter coercingConverter) { this.type = type; this.coercingConverter = coercingConverter; int higherIdx = -1; Class<?> current = type; while (current != Object.class) { for (final Field field : type.getDeclaredFields()) { final Csv csv = field.getAnnotation(Csv.class); if (csv != null) { final int pos = csv.index(); final String name = csv.name(); final boolean defaultName = Csv.DEFAULT_NAME.equals(name); // put each field a single time to avoid to set it twice even if position and name are filled for header output if (pos >= 0) { if (fieldByPosition.put(pos, field) != null) { throw new IllegalArgumentException("multiple field for index " + pos + " in " + type); }// w w w . j a v a 2 s . c o m if (!defaultName) { headers.put(pos, name); } } else if (!defaultName) { if (fieldByName.put(name, field) != null) { throw new IllegalArgumentException("multiple field for name '" + name + "' in " + type); } } if (pos > higherIdx) { higherIdx = pos; } if (!field.isAccessible()) { field.setAccessible(true); } } } current = current.getSuperclass(); } maxIndex = higherIdx; }
From source file:com.gatf.generator.core.GatfTestGeneratorMojo.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private Object getObject(Class claz, List<Type> heirarchies) throws Exception { if (claz.isEnum()) return claz.getEnumConstants()[0]; if (isMap(claz)) { return getMapValue(claz, claz.getTypeParameters(), heirarchies); } else if (isCollection(claz)) { return getListSetValue(claz, claz.getTypeParameters(), heirarchies); } else if (claz.isInterface() || Modifier.isAbstract(claz.getModifiers())) { return null; }/* ww w . j a v a2 s . c o m*/ if (heirarchies.contains(claz) || heirarchies.size() >= 2) return null; heirarchies.add(claz); Constructor cons = null; try { cons = claz.getConstructor(new Class[] {}); } catch (Exception e) { getLog().error("No public no-args constructor found for class " + claz.getName()); return null; } Object object = cons.newInstance(new Object[] {}); List<Field> allFields = getAllFields(claz); for (Field field : allFields) { if (Modifier.isStatic(field.getModifiers())) continue; if (!field.isAccessible()) { field.setAccessible(true); } List<Type> fheirlst = new ArrayList<Type>(heirarchies); if (isDebugEnabled()) getLog().info("Parsing Class " + getHeirarchyStr(fheirlst) + " field " + field.getName() + " type " + field.getType().equals(boolean.class)); if (isPrimitive(field.getType())) { field.set(object, getPrimitiveValue(field.getType())); } else if (isMap(field.getType())) { ParameterizedType type = (ParameterizedType) field.getGenericType(); field.set(object, getMapValue(field.getType(), type.getActualTypeArguments(), fheirlst)); } else if (isCollection(field.getType())) { ParameterizedType type = (ParameterizedType) field.getGenericType(); field.set(object, getListSetValue(field.getType(), type.getActualTypeArguments(), fheirlst)); } else if (!claz.equals(field.getType())) { Object fieldval = getObject(field.getType(), fheirlst); field.set(object, fieldval); } else if (claz.equals(field.getType())) { if (isDebugEnabled()) getLog().info("Ignoring recursive fields..."); } } return object; }
From source file:la2launcher.MainFrame.java
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel(); int srow = jTable1.getSelectedRow(); if (srow < 0) { return;//from w w w . j av a 2 s. co m } Integer procid = (Integer) dtm.getValueAt(srow, 0); for (Process proc : procs) { if ((proc.hashCode() + "").equals(procid.toString())) { try { Field field = proc.getClass().getDeclaredField("handle"); if (!field.isAccessible()) { field.setAccessible(true); } long pid = field.getLong(proc); Kernel32 kernel = Kernel32.INSTANCE; W32API.HANDLE handle = new W32API.HANDLE(); handle.setPointer(Pointer.createConstant(pid)); long pid_ = kernel.GetProcessId(handle); User32 u32 = User32.INSTANCE; u32.EnumWindows(new WinUser.WNDENUMPROC() { @Override public boolean callback(WinDef.HWND hwnd, Pointer pntr) { char[] windowText = new char[512]; u32.GetWindowText(hwnd, windowText, 512); String wText = Native.toString(windowText); if (wText.isEmpty()) { return true; } if (wText.equals("Lineage II")) { //TODO: 111 IntByReference pid__ = new IntByReference(); u32.GetWindowThreadProcessId(hwnd, pid__); if ((pid__.getValue() + "").equals(pid_ + "")) { u32.SetForegroundWindow(hwnd); lastHWND = hwnd; } } return true; } }, null); } catch (NoSuchFieldException ex) { Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (SecurityException ex) { Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalArgumentException ex) { Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } } } }