반영 일반 get 필드 값
반성을 통해 필드의 가치를 얻으려고 합니다.문제는 필드의 종류를 몰라서 값을 얻으면서 결정해야 한다는 것입니다.
이 코드는 다음과 같은 예외와 함께 발생합니다.
java.lang을 설정할 수 없습니다.문자열 필드 com....fieldName에서 java.lang으로 이동합니다.스트링
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);
기본 설정 클래스의 toString() 구현에 있는 리플렉션을 사용하여 클래스 멤버와 값을 확인합니다(간단하고 빠른 디버깅).
사용하고 있는 간단한 코드:
@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();
}
저도 찾아봤는데 도움이 됐으면 좋겠어요.
당신이 무엇을 달성하려고 하는지는 잘 모르겠지만, 당신의 코드에서 명백한 오류를 발견했습니다.Field.get()
는 필드를 포함하는 개체를 인수로 예상하고 해당 필드의 일부(예측값) 값을 요구합니다.그래서 당신은field.get(object)
.
필드 값을 찾고 있는 것처럼 보이므로 다음과 같이 얻을 수 있습니다.
Object objectValue = field.get(object);
필드 유형을 인스턴스화하고 빈/기본값을 작성할 필요가 없습니다. 또는 누락된 항목이 있을 수 있습니다.
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();
}
`
//Here is the example I used for get the field name also the field value
//Hope This will help to someone
TestModel model = new TestModel ("MyDate", "MyTime", "OUT");
//Get All the fields of the class
Field[] fields = model.getClass().getDeclaredFields();
//If the field is private make the field to accessible true
fields[0].setAccessible(true);
//Get the field name
System.out.println(fields[0].getName());
//Get the field value
System.out.println(fields[0].get(model));
`
Kotlin에 솔루션을 게시하지만 Java 객체에서도 사용할 수 있습니다.어떤 오브젝트라도 이 기능을 사용할 수 있도록 함수 확장을 만듭니다.
fun Any.iterateOverComponents() {
val fields = this.javaClass.declaredFields
fields.forEachIndexed { i, field ->
fields[i].isAccessible = true
// get value of the fields
val value = fields[i].get(this)
// print result
Log.w("Msg", "Value of Field "
+ fields[i].name
+ " is " + value)
}}
다음 웹 페이지를 보십시오.https://www.geeksforgeeks.org/field-get-method-in-java-with-examples/
잘못된 인수로 get을 호출하고 있습니다.
다음 중 하나여야 합니다.
Object value = field.get(object);
언급URL : https://stackoverflow.com/questions/13400075/reflection-generic-get-field-value
'programing' 카테고리의 다른 글
C/C++에서 부호 없는 좌회전 전 마스킹이 너무 편집증적인가요? (0) | 2022.08.15 |
---|---|
프로세스 내부에서 CPU 및 메모리 소비량을 확인하는 방법 (0) | 2022.08.15 |
Linux에서 시간 측정 - 시간 vs 클럭 vs getrusage vs clock_gettime vs gettime vs timespec_get? (0) | 2022.08.15 |
nuxt Auth Module과 vuex-persist의 비교 가능성 문제가 있습니까? (0) | 2022.08.15 |
인접 인터페이스의 Java 스위치가 케이스가 추가되면 더 빨리 동작하는 것처럼 보이는 이유는 무엇입니까? (0) | 2022.08.15 |