Last active
December 29, 2016 02:00
-
-
Save eyeahs/3c8272a0fa3a93781aa089af1aa7b3ce to your computer and use it in GitHub Desktop.
Reflection of overloaded methods
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
public class DefaultInjectingHelper { | |
public static void main(String[] args) { | |
final Component component = new ComponentMockImpl(); | |
final BaseDependecy a = new A(); | |
injectWithReflection(component, a); | |
} | |
public void injectWithReflection(Component component, Object target) throws InterruptedException { | |
try { | |
final Method method = component.getClass().getMethod("inject", new Class[]{target.getClass()}); | |
method.invoke(component, target); | |
} catch (NoSuchMethodException e) { | |
e.printStackTrace(); | |
} catch (IllegalAccessException e) { | |
e.printStackTrace(); | |
} catch (InvocationTargetException e) { | |
e.printStackTrace(); | |
} | |
} | |
public static class ComponentMockImpl implements Target { | |
@Override | |
public void inject(A a) { | |
System.out.println("A is called"); | |
} | |
@Override | |
public void inject(B b) { | |
System.out.println("B is called"); | |
} | |
} | |
public interface Component { | |
void inject(A a); | |
void inject(B b); | |
} | |
public static class BaseDependecy {} | |
public static class A extends BaseDependecy {} | |
public static class B extends BaseDependecy {} | |
} |
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
// https://github.com/google/dagger/issues/128 | |
private void injectWithReflectionFromDaggerComponent(Object obj) { | |
Method[] methods = AppComponent.class.getMethods(); | |
for(Method method : methods) { | |
Class<?>[] parameterTypes = method.getParameterTypes(); | |
if(parameterTypes.length == 1) { | |
Class<?> injectableClass = parameterTypes[0]; | |
if(injectableClass != null && injectableClass.equals(obj.getClass())) { | |
try { | |
method.invoke(getAppComponent(), obj); | |
} catch (Exception e) { | |
throw new IllegalStateException(String.format("Could not get inject using method %s in AppComponent", method), e); | |
} | |
} | |
} | |
} | |
throw new IllegalStateException("no inject method found for " + obj); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment