1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package android.hardware.camera2.dispatch;
17 
18 
19 import java.lang.reflect.Method;
20 
21 import static com.android.internal.util.Preconditions.*;
22 
23 /**
24  * Duck typing dispatcher; converts dispatch methods calls from one class to another by
25  * looking up equivalently methods at runtime by name.
26  *
27  * <p>For example, if two types have identical method names and arguments, but
28  * are not subclasses/subinterfaces of each other, this dispatcher will allow calls to be
29  * made from one type to the other.</p>
30  *
31  * @param <TFrom> source dispatch type, whose methods with {@link #dispatch} will be called
32  * @param <T> destination dispatch type, methods will be converted to the class of {@code T}
33  */
34 public class DuckTypingDispatcher<TFrom, T> implements Dispatchable<TFrom> {
35 
36     private final MethodNameInvoker<T> mDuck;
37 
38     /**
39      * Create a new duck typing dispatcher.
40      *
41      * @param target destination dispatch type, methods will be redirected to this dispatcher
42      * @param targetClass destination dispatch class, methods will be converted to this class's
43      */
DuckTypingDispatcher(Dispatchable<T> target, Class<T> targetClass)44     public DuckTypingDispatcher(Dispatchable<T> target, Class<T> targetClass) {
45         checkNotNull(targetClass, "targetClass must not be null");
46         checkNotNull(target, "target must not be null");
47 
48         mDuck = new MethodNameInvoker<T>(target, targetClass);
49     }
50 
51     @Override
dispatch(Method method, Object[] args)52     public Object dispatch(Method method, Object[] args) {
53         return mDuck.invoke(method.getName(), args);
54     }
55 }
56