Skip to content

Commit

Permalink
Merge pull request #579 from asibross/java-11
Browse files Browse the repository at this point in the history
Fix for reflectively calling default methods in Java 11
  • Loading branch information
elandau authored Aug 26, 2019
2 parents 8e98173 + 829f777 commit 069f7cf
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 52 deletions.
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
language: java
jdk:
- oraclejdk8
- openjdk8
sudo: false
install: ./installViaTravis.sh
script: ./buildViaTravis.sh
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,13 @@
import com.netflix.archaius.api.annotations.Configuration;
import com.netflix.archaius.api.annotations.DefaultValue;
import com.netflix.archaius.api.annotations.PropertyName;
import org.apache.commons.lang3.SystemUtils;
import org.apache.commons.lang3.text.StrSubstitutor;

import javax.inject.Inject;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
Expand All @@ -33,32 +37,28 @@
import java.util.function.Supplier;
import java.util.stream.Collectors;

import javax.inject.Inject;

import org.apache.commons.lang3.text.StrSubstitutor;

/**
* Factory for binding a configuration interface to properties in a {@link PropertyFactory}
* instance. Getter methods on the interface are mapped by naming convention
* by the property name may be overridden using the @PropertyName annotation.
*
*
* For example,
* <pre>
* {@code
* {@code
* {@literal @}Configuration(prefix="foo")
* interface FooConfiguration {
* int getTimeout(); // maps to "foo.timeout"
*
*
* String getName(); // maps to "foo.name"
* }
* }
* </pre>
*
*
* Default values may be set by adding a {@literal @}DefaultValue with a default value string. Note
* that the default value type is a string to allow for interpolation. Alternatively, methods can
* that the default value type is a string to allow for interpolation. Alternatively, methods can
* provide a default method implementation. Note that {@literal @}DefaultValue cannot be added to a default
* method as it would introduce ambiguity as to which mechanism wins.
*
*
* For example,
* <pre>
* {@code
Expand Down Expand Up @@ -173,25 +173,7 @@ static interface MethodInvoker<T> {
*/
T invoke(Object[] args);
}

static class DefaultMethodValueSupplier<T> implements Supplier<T> {
private final MethodHandle handle;

DefaultMethodValueSupplier(MethodHandle handle) {
this.handle = handle;
}

@SuppressWarnings("unchecked")
@Override
public T get() {
try {
return (T) handle.invokeWithArguments();
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
}

/**
* Abstract method invoker that encapsulates a property
* @param <T>
Expand Down Expand Up @@ -257,24 +239,15 @@ else if ("toString".equals(method.getName())) {
throw new NoSuchMethodError(method.getName() + " not found on interface " + type.getName());
}
};

// Hack so that default interface methods may be called from a proxy
final MethodHandles.Lookup lookup;
try {
Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class
.getDeclaredConstructor(Class.class, int.class);
constructor.setAccessible(true);
lookup = constructor.newInstance(type, MethodHandles.Lookup.PRIVATE);
} catch (Exception e) {
throw new RuntimeException("Failed to create temporary object for " + type.getName(), e);
}



final T proxyObject = (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[] { type }, handler);

for (Method m : type.getMethods()) {
try {
final MethodInvoker<?> invoker;

final String verb;
if (m.getName().startsWith("get")) {
verb = "get";
Expand All @@ -299,26 +272,26 @@ else if ("toString".equals(method.getName())) {
throw new IllegalArgumentException("@DefaultValue cannot be used with collections. Use default method implemenation instead "
+ m.getDeclaringClass().getName() + "#" + m.getName());
}

String value = m.getAnnotation(DefaultValue.class).value();
if (returnType == String.class) {
defaultSupplier = memoize((T) config.resolve(value));
} else {
defaultSupplier = memoize(decoder.decode(returnType, config.resolve(value)));
}
}
}

if (m.isDefault()) {
defaultSupplier = new DefaultMethodValueSupplier<T>(lookup.unreflectSpecial(m, type).bindTo(proxyObject));
defaultSupplier = createDefaultMethodSupplier(m, type, proxyObject);
}
final PropertyName nameAnnot = m.getAnnotation(PropertyName.class);

final PropertyName nameAnnot = m.getAnnotation(PropertyName.class);
final String propName = nameAnnot != null && nameAnnot.name() != null
? prefix + nameAnnot.name()
: prefix + Character.toLowerCase(m.getName().charAt(verb.length())) + m.getName().substring(verb.length() + 1);

propertyNames.put(m, propName);

if (returnType.equals(Map.class)) {
invoker = createMapProperty(propName, (ParameterizedType)m.getGenericReturnType(), LinkedHashMap::new, defaultSupplier);
} else if (returnType.equals(Set.class)) {
Expand Down Expand Up @@ -350,14 +323,49 @@ else if ("toString".equals(method.getName())) {
throw new RuntimeException("Error proxying method " + m.getName(), e);
}
}

return proxyObject;
}

private static <T> Supplier<T> memoize(T value) {
return () -> value;
}


private static <T> Supplier<T> createDefaultMethodSupplier(Method method, Class<T> type, T proxyObject) {
final MethodHandle methodHandle;

try {
if (SystemUtils.IS_JAVA_1_8) {
Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class
.getDeclaredConstructor(Class.class, int.class);
constructor.setAccessible(true);
methodHandle = constructor.newInstance(type, MethodHandles.Lookup.PRIVATE)
.unreflectSpecial(method, type)
.bindTo(proxyObject);
}
else {
// Java 9 onwards
methodHandle = MethodHandles.lookup()
.findSpecial(type,
method.getName(),
MethodType.methodType(method.getReturnType(), new Class[0]),
type)
.bindTo(proxyObject);
}
} catch (Throwable e) {
throw new RuntimeException("Failed to create temporary object for " + type.getName(), e);
}

return () -> {
try {
//noinspection unchecked
return (T) methodHandle.invokeWithArguments();
} catch (Throwable e) {
throw new RuntimeException(e);
}
};
}

@SuppressWarnings({ "rawtypes", "unchecked" })
private <T> MethodInvoker<T> createCollectionProperty(String propName, ParameterizedType type, Supplier<Collection<T>> collectionFactory, Supplier<T> next) {
final Class valueType = (Class) type.getActualTypeArguments()[0];
Expand Down

0 comments on commit 069f7cf

Please sign in to comment.