Last active
August 25, 2016 18:20
-
-
Save wreulicke/96849bc11054d8e4f7083302e3517bb0 to your computer and use it in GitHub Desktop.
AnnotationによるEnumのFieldのデフォルト引数実装
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
@Target(ElementType.FIELD) | |
@Retention(RetentionPolicy.RUNTIME) | |
@interface Default{ | |
String value() default "test"; | |
} | |
enum Test{ | |
@Default FOO,BAR; | |
String value; | |
Test(){ | |
Function<String, Optional<Field>> fieldGetter=createFieldGetter(this.getClass()); | |
fieldGetter.apply(this.toString()) | |
.flatMap(enun->Optional.ofNullable(enun.getAnnotation(Default.class))) | |
.ifPresent(annotation->{ | |
Arrays.stream(annotation.annotationType().getDeclaredMethods()) | |
.forEach(method->{ | |
fieldGetter.apply(method.getName()) | |
.filter(field->field.getType().isAssignableFrom(method.getReturnType())) | |
.ifPresent(field->{ | |
try { | |
field.set(this, method.invoke(annotation)); | |
} catch (IllegalAccessException|InvocationTargetException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
}); | |
}); | |
}); | |
System.out.println(this.value); | |
} | |
// ラムダ内で発生した例外を握りつぶせなかったのでボツ | |
<T> Optional<T> getValue(Supplier<T> f, Class<? extends Exception>... exceptions ) { | |
try{ | |
return Optional.ofNullable(f.get()); | |
}catch(Exception e){ | |
return Optional.empty(); | |
} | |
} | |
Function<String, Optional<Field>> createFieldGetter(Class<?> clazz){ | |
return (name) -> Hoge.getField(clazz, name); | |
} | |
Optional<Field> getField(Class<?> clazz,String name){ | |
try { | |
return Optional.ofNullable(clazz.getDeclaredField(name)); | |
} catch (NoSuchFieldException | SecurityException e) { | |
//全てを握りつぶすマン!! | |
} | |
return Optional.empty(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment