1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| import com.fasterxml.jackson.databind.ObjectMapper; import com.mwk.entity.Schoolbag; import com.mwk.entity.Student;
import java.util.Objects; import java.util.Optional;
public final class MyOptional {
public static <T> T getValueByField(Object source, String filed, final Class<T> vClass) { Objects.requireNonNull(filed); String[] filedNames = filed.split("\\."); Object oldTemp; if (filedNames.length == 1) { oldTemp = ReflectionUtil.invokeGetterMethodNoThrowException(source, filed); return new ObjectMapper().convertValue(oldTemp, vClass); } oldTemp = ReflectionUtil.invokeGetterMethodNoThrowException(source, getFirstStrByPoint(filed)); if (Objects.isNull(oldTemp)) { return null; } oldTemp = getValueByField(oldTemp, getEndStrByPoint(filed), vClass); return new ObjectMapper().convertValue(oldTemp, vClass); }
public static <T> Optional<T> ofNullable(Object source, String filed, final Class<T> vClass) { return Optional.ofNullable(getValueByField(source, filed, vClass)); }
private static String getFirstStrByPoint(String str) { return str.substring(0, str.indexOf(".")); }
private static String getEndStrByPoint(String str) { return str.substring(str.indexOf(".") + 1); }
public static void main(String[] args) { Student student = new Student("李明", new Schoolbag("黄色", null));
System.out.println(getValueByField(student, "name", String.class)); System.out.println(getValueByField(student, "bag", Schoolbag.class)); System.out.println(getValueByField(student, "bag", Schoolbag.class).getColor()); System.out.println(getValueByField(student, "bag.color", String.class)); System.out.println(getValueByField(student, "bag.pencilCase.num", Integer.class));
System.out.println(getValueByField(student, "ww.ee.num", Integer.class)); System.out.println(getValueByField(student, "bag.ee.num", Integer.class)); System.out.println(getValueByField(null, "bag.ee.num", Integer.class));
System.out.println("-----------被Optional修饰的方法------------"); System.out.println(ofNullable(student, "bag", Schoolbag.class).map(Schoolbag::getColor).orElse("无色")); System.out.println(ofNullable(student, "name", String.class)); System.out.println(ofNullable(student, "bag", Schoolbag.class).isPresent()); System.out.println(ofNullable(null, "bag.ee.num", Integer.class).orElse(0)); System.out.println(ofNullable(null, "bag.ee.num", Integer.class).get());
}
}
|