Created
June 27, 2024 08:13
-
-
Save shortthirdman/79f929d85d57f88888a07b5aab3d102f to your computer and use it in GitHub Desktop.
Java Reflection Utils
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.reflect.Field; | |
public class ReflectionUtils { | |
public static <T> T getOrDefault(T object, String propertyName, Class<T> clazz, T defaultValue) { | |
try { | |
// Get the field by name | |
Field field = object.getClass().getDeclaredField(propertyName); | |
// Ensure field is accessible | |
field.setAccessible(true); | |
// Get the value of the field | |
Object value = field.get(object); | |
// Check if the value is null, return default value if null | |
if (value == null) { | |
return defaultValue; | |
} | |
// Check if the value is of the correct type, otherwise return default value | |
if (clazz.isInstance(value)) { | |
return clazz.cast(value); | |
} else { | |
return defaultValue; | |
} | |
} catch (NoSuchFieldException | IllegalAccessException | ClassCastException e) { | |
// In case of any exception, return default value | |
return defaultValue; | |
} | |
} | |
public static void main(String[] args) { | |
// Example usage | |
MyClass myObject = new MyClass(); | |
String result = getOrDefault(myObject, "myString", String.class, "defaultString"); | |
System.out.println(result); // This will print the value of myString if it exists, otherwise "defaultString" | |
} | |
} | |
class MyClass { | |
private String myString = "Hello"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment