Java Code Examples for java.lang.reflect.Field.getName()

The following are Jave code examples for showing how to use getName() of the java.lang.reflect.Field class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: excel-util4j   File: ValueConvertConvertor.java   View Source Code Vote up 6 votes
@Override
public Object convert(Object obj, Field field, Map<String, Object> excelRecordMap) {

    logger.trace("field: " + field.getName() +
                    ", obj: " + obj +
                    " run ValueConvertConvertor");

    try {
        Class<? extends Convertor>[] convertorClazzes = field.getAnnotation(ValueConvert.class).value();
        for (Class<? extends Convertor> convertorClazz : convertorClazzes) {
            Convertor convertor = convertorClazz.newInstance();
            obj = convertor.convert(obj, field, excelRecordMap);
        }
        return obj;

    } catch (Exception e) {
        throw new RuntimeException("field注解ValueConvert转换错误,filed:" + field.getName(), e);
    }
}
 
Example 2
Project: FApkSigner   File: Asn1BerParser.java   View Source Code Vote up 6 votes
public static void setFieldValue(
        Object obj, Field field, Asn1Type type, BerDataValue dataValue)
                throws Asn1DecodingException {
    try {
        switch (type) {
            case SET_OF:
            case SEQUENCE_OF:
                if (Asn1OpaqueObject.class.equals(field.getType())) {
                    field.set(obj, convert(type, dataValue, field.getType()));
                } else {
                    field.set(obj, parseSetOf(dataValue, getElementType(field)));
                }
                return;
            default:
                field.set(obj, convert(type, dataValue, field.getType()));
                break;
        }
    } catch (ReflectiveOperationException e) {
        throw new Asn1DecodingException(
                "Failed to set value of " + obj.getClass().getName()
                        + "." + field.getName(),
                e);
    }
}
 
Example 3
Project: drinkwater-java   File: BeanFactory.java   View Source Code Vote up 6 votes
private static Object injectFields(Object bean,
                                   IServiceConfiguration config,
                                   IPropertyResolver propertyresolver) throws Exception {

    if (config.getInjectionStrategy() == InjectionStrategy.Default) {
        for (Field f : bean.getClass().getDeclaredFields()) {
            String propertyUri = f.getName() + ":undefined";
            String value = propertyresolver.lookupProperty(propertyUri);

            if (!"undefined".equals(value)) {
                Object convertedValue = propertyresolver.lookupProperty(f.getType(),propertyUri);

                f.setAccessible(true);
                f.set(bean, convertedValue);
            }
        }
    }

    return bean;

}
 
Example 4
Project: excel-util4j   File: DateFormatConvertor.java   View Source Code Vote up 6 votes
@Override
public Object convert(Object obj, Field field, Map<String, Object> excelRecordMap) {

    logger.trace("field: " + field.getName() +
                    ", obj: " + obj +
                    " run DateFormatConvertor");

    if (obj == null) return null;
    if (obj instanceof Date) return obj;
    Date date;
    try {
        String dateFormat = field.getAnnotation(DateFormat.class).value();
        if (StringUtils.isBlank(dateFormat))
            throw new RuntimeException("field注解DateFormat值为空,filed:" + field.getName());

        logger.debug(dateFormat);

        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        date = sdf.parse(obj.toString());
        return date;

    } catch (Exception e) {
        throw new RuntimeException("field注解DateFormat转换错误,filed:" + field.getName(), e);
    }
}
 
Example 5
Project: Phoenicia   File: Model.java   View Source Code Vote up 6 votes
public static final <O extends Model, T extends Model> String getBackLinkFieldName(
		
		Class<O> originClass,
		Class<T> targetClass
		
) {
	
	Field fk = null;
	
	try {
		fk = getForeignKeyField(targetClass, originClass, getInstace(originClass));
	}  catch (IllegalAccessException e) {
		Log.e(TAG, "an exception has been thrown trying to gather the foreign key field pointing to " 
				+ targetClass.getSimpleName() 
				+ " from origin class " 
				+ originClass.getSimpleName(), e);
	}
	
	if(fk != null) {
		return fk.getName();
	}
	
	return null;
}
 
Example 6
Project: neto   File: NetoValidator.java   View Source Code Vote up 6 votes
private static void validateField(Field field, Object target) throws IllegalArgumentException, IllegalAccessException {
    field.setAccessible(true);
    Object value = field.get(target);
    if (field.isAnnotationPresent(NetoNotNull.class)) {
        if (value == null) {
            throw new ValidationException(Constants.StatusCode.PARAMETER_NULL, field.getName() + " is null");
        }
    } else if (field.isAnnotationPresent(NetoNotNullOrNotEmpty.class)) {

        if (value == null) {
            throw new ValidationException(Constants.StatusCode.PARAMETER_NULL, field.getName() + " is null");
        }

        if (value instanceof String && (value == null || ((String) value).isEmpty())) {
            throw new ValidationException(Constants.StatusCode.PARAMETER_NULL_OR_EMPTY, field.getName() + " is null or empty");
        }
    }
}
 
Example 7
Project: nh-micro   File: MicroBeanMapUtil.java   View Source Code Vote up 6 votes
public static Map getFieldMap(Class cls) {
	Map map = new HashMap();
	Field[] fields = cls.getDeclaredFields();
	int size = fields.length;
	for (int i = 0; i < size; i++) {
		Field field = fields[i];
		MicroMappingAnno anno = field.getAnnotation(MicroMappingAnno.class);
		if (anno == null) {
			continue;
		}
		String keyName = anno.name();
		String fieldName = field.getName();
		map.put(fieldName, keyName);
	}
	return map;
}
 
Example 8
Project: dubbox-hystrix   File: JavaDeserializer.java   View Source Code Vote up 6 votes
static void logDeserializeError(Field field, Object obj, Object value,
                                Throwable e)
  throws IOException
{
  String fieldName = (field.getDeclaringClass().getName()
                      + "." + field.getName());

  if (e instanceof HessianFieldException)
    throw (HessianFieldException) e;
  else if (e instanceof IOException)
    throw new HessianFieldException(fieldName + ": " + e.getMessage(), e);
  
  if (value != null)
    throw new HessianFieldException(fieldName + ": " + value.getClass().getName() + " (" + value + ")"
		      + " cannot be assigned to '" + field.getType().getName() + "'", e);
  else
     throw new HessianFieldException(fieldName + ": " + field.getType().getName() + " cannot be assigned from null", e);
}
 
Example 9
Project: Sikulix2tesseract   File: Utils.java   View Source Code Vote up 6 votes
/**
 * Gets user-friendly name of the public static final constant defined in a
 * class or an interface for display purpose.
 *
 * @param value the constant value
 * @param c type of class or interface
 * @return name
 */
public static String getConstantName(Object value, Class c) {
    for (Field f : c.getDeclaredFields()) {
        int mod = f.getModifiers();
        if (Modifier.isStatic(mod) && Modifier.isPublic(mod) && Modifier.isFinal(mod)) {
            try {
                if (f.get(null).equals(value)) {
                    return f.getName();
                }
            } catch (IllegalAccessException e) {
                return String.valueOf(value);
            }
        }
    }
    return String.valueOf(value);
}
 
Example 10
Project: openjdk-jdk10   File: IDLTypesUtil.java   View Source Code Vote up 5 votes
/**
 * Implements 1.2.3 #6
 */
private void validateConstants(final Class c)
    throws IDLTypeException {

    Field[] fields = null;

    try {
        fields = (Field[])
            java.security.AccessController.doPrivileged
            (new java.security.PrivilegedExceptionAction() {
                    public java.lang.Object run() throws Exception {
                        return c.getFields();
                    }
                });
    } catch(java.security.PrivilegedActionException pae) {
        IDLTypeException ite = new IDLTypeException();
        ite.initCause(pae);
        throw ite;
    }

    for(int i = 0; i < fields.length; i++) {
        Field next = fields[i];
        Class fieldType = next.getType();
        if( (fieldType != java.lang.String.class) &&
            !isPrimitive(fieldType) ) {
            String msg = "Constant field '" + next.getName() +
                "' in class '" + next.getDeclaringClass().getName() +
                "' has invalid type' " + next.getType() + "'. Constants" +
                " in RMI/IIOP interfaces can only have primitive" +
                " types and java.lang.String types.";
            throw new IDLTypeException(msg);
        }
    }


    return;
}
 
Example 11
Project: openjdk-jdk10   File: MemberName.java   View Source Code Vote up 5 votes
@SuppressWarnings("LeakingThisInConstructor")
public MemberName(Field fld, boolean makeSetter) {
    Objects.requireNonNull(fld);
    // fill in vmtarget, vmindex while we have fld in hand:
    MethodHandleNatives.init(this, fld);
    assert(isResolved() && this.clazz != null);
    this.name = fld.getName();
    this.type = fld.getType();
    assert((REF_putStatic - REF_getStatic) == (REF_putField - REF_getField));
    byte refKind = this.getReferenceKind();
    assert(refKind == (isStatic() ? REF_getStatic : REF_getField));
    if (makeSetter) {
        changeReferenceKind((byte)(refKind + (REF_putStatic - REF_getStatic)), refKind);
    }
}
 
Example 12
Project: Reer   File: FieldOptionElement.java   View Source Code Vote up 5 votes
private static String calOptionName(Option option, Field field) {
    if (option.option().length() == 0) {
        return field.getName();
    } else {
        return option.option();
    }
}
 
Example 13
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: MixAll.java   View Source Code Vote up 5 votes
public static void printObjectProperties(final Logger log, final Object object, final boolean onlyImportantField) {
    Field[] fields = object.getClass().getDeclaredFields();
    for (Field field : fields) {
        if (!Modifier.isStatic(field.getModifiers())) {
            String name = field.getName();
            if (!name.startsWith("this")) {
                Object value = null;
                try {
                    field.setAccessible(true);
                    value = field.get(object);
                    if (null == value) {
                        value = "";
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

                if (onlyImportantField) {
                    Annotation annotation = field.getAnnotation(ImportantField.class);
                    if (null == annotation) {
                        continue;
                    }
                }

                if (log != null) {
                    log.info(name + "=" + value);
                }
            }
        }
    }
}
 
Example 14
Project: tasfe-framework   File: BaseInterceptor.java   View Source Code Vote up 5 votes
/**
 * 设置bean 属性值
 *
 * @param map
 * @param bean
 * @throws Exception
 */
public static void setFieldValue(Map<Object, Object> map, Object bean) throws Exception {
    Class<?> cls = bean.getClass();
    Method methods[] = cls.getDeclaredMethods();
    Field fields[] = cls.getDeclaredFields();

    for (Field field : fields) {
        String fldtype = field.getType().getSimpleName();
        String fldSetName = field.getName();
        String setMethod = pareSetName(fldSetName);
        if (!checkMethod(methods, setMethod)) {
            continue;
        }
        if (!map.containsKey(fldSetName)) {
            continue;
        }
        Object value = map.get(fldSetName);
        System.out.println(value.toString());
        Method method = cls.getMethod(setMethod, field.getType());
        System.out.println(method.getName());
        if (null != value) {
            if ("String".equals(fldtype)) {
                method.invoke(bean, (String) value);
            } else if ("Double".equals(fldtype)) {
                method.invoke(bean, (Double) value);
            } else if ("int".equals(fldtype)) {
                int val = Integer.valueOf((String) value);
                method.invoke(bean, val);
            } else {
                method.invoke(bean, value);
            }
        }

    }
}
 
Example 15
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: RemotingCommand.java   View Source Code Vote up 5 votes
/**
 * 编码过程
 */
public void makeCustomHeaderToNet() {
    if (this.customHeader != null) {
        Field[] fields = getClazzFields(customHeader.getClass());
        if (null == this.extFields) {
            this.extFields = new HashMap<String, String>();
        }

        for (Field field : fields) {
            if (!Modifier.isStatic(field.getModifiers())) {
                String name = field.getName();
                if (!name.startsWith("this")) {
                    Object value = null;
                    try {
                        field.setAccessible(true);
                        value = field.get(this.customHeader);
                    } catch (Exception e) {
                        log.error("Failed to access field [{}]", name, e);
                    }

                    if (value != null) {
                        this.extFields.put(name, value.toString());
                    }
                }
            }
        }
    }
}
 
Example 16
Project: ProtocolSupportPocketStuff   File: TeamsPacketListener.java   View Source Code Vote up 5 votes
public static Object get(Field field, Object source) {
	try {
		return field.get(source);
	} catch (Exception e) {
		e.printStackTrace();
	}
	throw new RuntimeException("Error while getting field \"" + field.getName() + "\" from " + source + "!");
}
 
Example 17
Project: JRediClients   File: EntityUtils.java   View Source Code Vote up 5 votes
/**
 * 获取所有需要保存到Redis和DB数据库的缓存的字段跟值
 * 
 * @param iEntity
 * @return
 */
public static Map<String, String> getCacheValueMap(IEntity iEntity, EntitySaveEnum type) {
	Map<String, String> map = new HashMap<>();
	Field[] fields = getAllCacheFields(iEntity, type);
	for (Field field : fields) {
		String fieldName = field.getName();
		String value = ObjectUtils.getFieldsValueStr(iEntity, fieldName);
		map.put(fieldName, value);
	}
	return map;
}
 
Example 18
Project: Poetry   File: OrmliteReflection.java   View Source Code Vote up 5 votes
/**
 * Get SQLite column name for a given Field.
 *
 * @param field         the model's field
 * @param databaseField the DatabaseField annotation for the specified Field
 * @return the SQLite column name
 */
public static String getFieldName(Field field, DatabaseField databaseField) {
	if (!databaseField.columnName().isEmpty()) {
		return databaseField.columnName();
	} else if (OrmliteReflection.isForeign(databaseField)) {
		return field.getName() + FOREIGN_ID_FIELD_SUFFIX;
	} else {
		return field.getName();
	}
}
 
Example 19
Project: firebase-admin-java   File: CustomClassMapper.java   View Source Code Vote up 4 votes
private static String propertyName(Field field) {
  String annotatedName = annotatedName(field);
  return annotatedName != null ? annotatedName : field.getName();
}
 
Example 20
Project: CodeBroker   File: DefaultSFSDataSerializer.java   View Source Code Vote up 4 votes
private void convertPojo(Object pojo, IObject sfsObj)
        throws IllegalAccessException, NoSuchMethodException, IllegalArgumentException {
    Class pojoClazz = pojo.getClass();
    String classFullName = pojoClazz.getCanonicalName();
    if (classFullName == null) {
        throw new IllegalArgumentException("Anonymous classes cannot be serialized!");
    } else if (!(pojo instanceof SerializableType)) {
        throw new IllegalStateException("Cannot serialize object: " + pojo + ", type: " + classFullName
                + " -- It doesn\'t implement the SerializableSFSType interface");
    } else {
        CArray fieldList = CArray.newInstance();
        sfsObj.putUtfString(CLASS_MARKER_KEY, classFullName);
        sfsObj.putSFSArray(CLASS_FIELDS_KEY, fieldList);
        Field[] var9;
        int var8 = (var9 = pojoClazz.getDeclaredFields()).length;

        for (int var7 = 0; var7 < var8; ++var7) {
            Field field = var9[var7];

            try {
                int err = field.getModifiers();
                if (!Modifier.isTransient(err) && !Modifier.isStatic(err)) {
                    String fieldName = field.getName();
                    Object fieldValue = null;
                    if (Modifier.isPublic(err)) {
                        fieldValue = field.get(pojo);
                    } else {
                        fieldValue = this.readValueFromGetter(fieldName, field.getType().getSimpleName(), pojo);
                    }

                    CObject fieldDescriptor = CObject.newInstance();
                    fieldDescriptor.putUtfString(FIELD_NAME_KEY, fieldName);
                    fieldDescriptor.put(FIELD_VALUE_KEY, this.wrapPojoField(fieldValue));
                    fieldList.addSFSObject(fieldDescriptor);
                }
            } catch (Exception var14) {
                this.logger.info("-- No public getter -- Serializer skipping private field: " + field.getName()
                        + ", from class: " + pojoClazz);
                var14.printStackTrace();
            }
        }

    }
}