Skip to content

Instantly share code, notes, and snippets.

@stijnvanbael
Last active August 25, 2021 05:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stijnvanbael/5965616 to your computer and use it in GitHub Desktop.
Save stijnvanbael/5965616 to your computer and use it in GitHub Desktop.
Extender extends Java objects at runtime. Any object implementing an interface can be extended this way with new methods. Or it can be used to change the behaviour of existing methods. Also useful for duck typing.
/*
Copyright (c) 2017 Stijn Van Bael.
All rights reserved.
Redistribution and use in source and binary forms are permitted
provided that the above copyright notice and this paragraph are
duplicated in all such forms and that any documentation,
advertising materials, and other materials related to such
distribution and use acknowledge that the software was developed
by the <organization>. The name of the
<organization> may not be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.*;
import java.util.stream.Collectors;
/**
* <p>Extends an object with an interface with extra methods or overrides methods.</p>
* <p>
* <p>Example use:</p>
* <pre>
* List<String> list = new ArrayList<String>();
* List<String> extendedList = Extender.extend(list).with(new Object() {
* boolean add(Object e) {
* System.out.println("Adding " + e + " to the list.");
* list.add(e);
* }
* }).as(List.class);
* </pre>
*/
public final class Extender {
private Object objectToExtend;
private Object[] extensions = new Object[0];
private static final Map<ClassLoader, Map<String, Class<?>>> CLASS_CACHE = new HashMap<>();
private Extender(Object objectToExtend) {
this.objectToExtend = objectToExtend;
}
public static Extender extend(Object objectToExtend) {
return new Extender(objectToExtend);
}
public Extender with(Object... extensions) {
this.extensions = extensions;
return this;
}
public <T> T as(Class<T> expectedType) {
ClassLoader classLoader = expectedType.getClassLoader();
Set<Class<?>> interfaces = buildInterfaces(expectedType, objectToExtend, classLoader);
return expectedType.cast(Proxy.newProxyInstance(classLoader,
interfaces.toArray(new Class<?>[interfaces.size()]), (proxy, method, args) -> {
for (Object extension : extensions) {
try {
extension.getClass().getDeclaredMethod(method.getName(), (Class<?>[]) method.getParameterTypes());
return methodOf(extension, method).invoke(extension, args);
} catch (NoSuchMethodException e) {
// Not declared
}
}
return methodOf(objectToExtend, method).invoke(objectToExtend, args);
}));
}
private Method methodOf(Object extension, Method method) {
try {
return extension.getClass().getMethod(method.getName(), (Class<?>[]) method.getParameterTypes());
} catch (NoSuchMethodException e) {
throw new RuntimeException("Did not find " + method + " on " + extension.getClass(), e);
}
}
private static <T> Set<Class<?>> buildInterfaces(Class<T> expectedType, Object toDecorate, ClassLoader classLoader) {
Set<Class<?>> interfaces = new HashSet<>();
interfaces.addAll(allVisible(toDecorate.getClass().getInterfaces(), classLoader));
interfaces.add(expectedType);
return interfaces;
}
private static Collection<? extends Class<?>> allVisible(final Class<?>[] interfaces, final ClassLoader classLoader) {
return Arrays.stream(interfaces)
.filter((interfaceClass) -> {
try {
Class<?> actualClass = actualClassOf(interfaceClass, classLoader);
return actualClass == interfaceClass;
} catch (ClassNotFoundException e) {
return false;
}
}).collect(Collectors.toList());
}
private static Class<?> actualClassOf(Class<?> interfaceClass, ClassLoader classLoader) throws ClassNotFoundException {
Map<String, Class<?>> classesForClassLoader = CLASS_CACHE.get(classLoader);
String name = interfaceClass.getName();
if (classesForClassLoader == null) {
classesForClassLoader = new HashMap<>();
CLASS_CACHE.put(classLoader, classesForClassLoader);
}
if (classesForClassLoader.containsKey(name)) {
return classesForClassLoader.get(name);
}
Class<?> actualClass;
try {
actualClass = classLoader.loadClass(name);
} catch (ClassNotFoundException e) {
actualClass = null;
}
classesForClassLoader.put(name, actualClass);
return actualClass;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment