리플렉션 일반 Get 필드 값
리플렉션을 통해 필드 값을 받으려고합니다. 문제는 필드 유형을 모르고 값을 얻는 동안 결정해야한다는 것입니다.
이 코드는이 예외와 함께 발생합니다.
java.lang.String 필드 com .... fieldName을 java.lang.String으로 설정할 수 없습니다.
Field field = object.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
Class<?> targetType = field.getType();
Object objectValue = targetType.newInstance();
Object value = field.get(objectValue);
캐스팅을 시도했지만 컴파일 오류가 발생합니다.
field.get((targetType)objectValue)
또는
targetType objectValue = targetType.newInstance();
어떻게해야합니까?
이전에 대답 한 것처럼 다음을 사용해야합니다.
Object value = field.get(objectInstance);
때로는 선호되는 또 다른 방법은 게터를 동적으로 호출하는 것입니다. 예제 코드 :
public static Object runGetter(Field field, BaseValidationObject o)
{
// MZ: Find the correct method
for (Method method : o.getMethods())
{
if ((method.getName().startsWith("get")) && (method.getName().length() == (field.getName().length() + 3)))
{
if (method.getName().toLowerCase().endsWith(field.getName().toLowerCase()))
{
// MZ: Method found, run it
try
{
return method.invoke(o);
}
catch (IllegalAccessException e)
{
Logger.fatal("Could not determine method: " + method.getName());
}
catch (InvocationTargetException e)
{
Logger.fatal("Could not determine method: " + method.getName());
}
}
}
}
return null;
}
또한 클래스가 다른 클래스에서 상속 될 때 필드를 재귀 적으로 결정해야합니다. 예를 들어, 주어진 클래스의 모든 필드를 가져 오는 것;
for (Class<?> c = someClass; c != null; c = c.getSuperclass())
{
Field[] fields = c.getDeclaredFields();
for (Field classField : fields)
{
result.add(classField);
}
}
필드의 메소드 를 얻으려면 객체 를 전달해야 하므로
Field field = object.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
Object value = field.get(object);
I use the reflections in the toString() implementation of my preference class to see the class members and values (simple and quick debugging).
The simplified code I'm using:
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
Class<?> thisClass = null;
try {
thisClass = Class.forName(this.getClass().getName());
Field[] aClassFields = thisClass.getDeclaredFields();
sb.append(this.getClass().getSimpleName() + " [ ");
for(Field f : aClassFields){
String fName = f.getName();
sb.append("(" + f.getType() + ") " + fName + " = " + f.get(this) + ", ");
}
sb.append("]");
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
I hope that it will help someone, because I also have searched.
Integer typeValue = 0;
try {
Class<Types> types = Types.class;
java.lang.reflect.Field field = types.getDeclaredField("Type");
field.setAccessible(true);
Object value = field.get(types);
typeValue = (Integer) value;
} catch (Exception e) {
e.printStackTrace();
}
Although it's not really clear to me what you're trying to achieve, I spotted an obvious error in your code: Field.get()
expects the object which contains the field as argument, not some (possible) value of that field. So you should have field.get(object)
.
Since you appear to be looking for the field value, you can obtain that as:
Object objectValue = field.get(object);
No need to instantiate the field type and create some empty/default value; or maybe there's something I missed.
You are calling get with the wrong argument.
It should be:
Object value = field.get(object);
참고URL : https://stackoverflow.com/questions/13400075/reflection-generic-get-field-value
'Programing' 카테고리의 다른 글
STDIN에서 데이터를 읽는 동안 파일 압축 (0) | 2020.07.15 |
---|---|
OpenFileDialog의 여러 파일 확장자 (0) | 2020.07.15 |
asp.net에서 List <>를 List <>에 추가하는 방법 (0) | 2020.07.15 |
LocalDate를 문자열로 포맷하는 방법은 무엇입니까? (0) | 2020.07.15 |
MVC에서 기본 경로 (영역으로)를 설정하는 방법 (0) | 2020.07.15 |