申し訳ありませんが、ご使用の方法は広く受け入れられているようです。Spring や Maven などの大規模なライブラリのコード ベースには、そのようなコードがたくさん見られます。
ただし、代わりに、特定の入力から特定の出力に変換できるヘルパー インターフェイスを導入することもできます。このようなもの:
public interface Converter<I, O> {
boolean canConvert(I input);
O convert(I input);
}
とヘルパーメソッド
public static <I, O> O getDataFromConverters(
final I input,
final Converter<I, O>... converters
){
O result = null;
for(final Converter<I, O> converter : converters){
if(converter.canConvert(input)){
result = converter.convert(input);
break;
}
}
return result;
}
したがって、ロジックを実装する再利用可能なコンバーターを作成できます。canConvert(input)
各コンバーターは、その変換ルーチンを使用するかどうかを決定するメソッドを実装する必要があります。
実際、あなたのリクエストで思い出したのは、Prototype (Javascript)のTry.these(a,b,c)メソッドです。
あなたの場合の使用例:
検証メソッドを持ついくつかの Bean があるとします。これらの検証方法を見つける方法はいくつかあります。まず、この注釈が型に存在するかどうかを確認します。
// retention, target etc. stripped
public @interface ValidationMethod {
String value();
}
次に、「validate」というメソッドがあるかどうかを確認します。簡単にするために、すべてのメソッドが Object 型の単一のパラメーターを定義すると仮定します。別のパターンを選択することもできます。とにかく、ここにサンプルコードがあります:
// converter using the annotation
public static final class ValidationMethodAnnotationConverter implements
Converter<Class<?>, Method>{
@Override
public boolean canConvert(final Class<?> input){
return input.isAnnotationPresent(ValidationMethod.class);
}
@Override
public Method convert(final Class<?> input){
final String methodName =
input.getAnnotation(ValidationMethod.class).value();
try{
return input.getDeclaredMethod(methodName, Object.class);
} catch(final Exception e){
throw new IllegalStateException(e);
}
}
}
// converter using the method name convention
public static class MethodNameConventionConverter implements
Converter<Class<?>, Method>{
private static final String METHOD_NAME = "validate";
@Override
public boolean canConvert(final Class<?> input){
return findMethod(input) != null;
}
private Method findMethod(final Class<?> input){
try{
return input.getDeclaredMethod(METHOD_NAME, Object.class);
} catch(final SecurityException e){
throw new IllegalStateException(e);
} catch(final NoSuchMethodException e){
return null;
}
}
@Override
public Method convert(final Class<?> input){
return findMethod(input);
}
}
// find the validation method on a class using the two above converters
public static Method findValidationMethod(final Class<?> beanClass){
return getDataFromConverters(beanClass,
new ValidationMethodAnnotationConverter(),
new MethodNameConventionConverter()
);
}
// example bean class with validation method found by annotation
@ValidationMethod("doValidate")
public class BeanA{
public void doValidate(final Object input){
}
}
// example bean class with validation method found by convention
public class BeanB{
public void validate(final Object input){
}
}