サブクラスを手動で記述せずに、 @MyFormat アノテーションの値で書式設定された Date ではなく、Person インスタンスを受け取り、誕生日を文字列として返すクラスを生成するにはどうすればよいですか?
目的は、生成されたインスタンスを HTML ページの生成に使用することです。
class Person {
@MyFormat("%td.%<tm.%<tY")
public Date getBirthday() { return birthday; }
}
// Usage somewhere in the code
...
List<Person> people = people.parallelStream()
.map(p -> MyFormatInterceptor.wrap(p))
.collect(toCollection(ArrayList::new));
System.out.println(people.iterator().next().getBirtday()) // 31.Mai.2015
私はこれを持っています(下記参照)。
呼び出しは式 "person.birthday" の評価からのリフレクションによって行われるため、戻り値の型が Date から String に変更されても問題ありません。
new ByteBuddy()
.subclass(person.getClass())
.method(isAnnotatedWith(MyFormat.class))
.intercept(MethodDelegation.to(MyFormatInterceptor.class))
.make()
.load(person.getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
class MyFormatInterceptor {
@RuntimeType
public static Object format(@Origin Method m, @SuperCall Callable<?> zuper) {
MyFormat formatAnnotation = m.getAnnotation(MyFormat.class);
return String.format(formatAnnotation.value(), zuper.call());
}
}
したがって、新しいクラスのメソッド名は「String getBirthday()」と同じですが、戻り値は String になります。