Junior — Middle
What happens if you access a non-existent field of an object using reflection?
sobes.tech AI
Answer from AI
If you use reflection to access a non-existent field of an object in Android (Java/Kotlin), an exception will be thrown, usually a NoSuchFieldException. This means that the field with the specified name was not found in the class of the object. To avoid this, it is recommended to check for its existence or handle exceptions before accessing the field via reflection. Example in Java:
try {
Field field = obj.getClass().getDeclaredField("nonExistentField");
field.setAccessible(true);
Object value = field.get(obj);
} catch (NoSuchFieldException e) {
System.out.println("Field not found: " + e.getMessage());
} catch (IllegalAccessException e) {
System.out.println("No access to the field: " + e.getMessage());
}