Skip to content

Commit

Permalink
Replace switch with reflection in generated code
Browse files Browse the repository at this point in the history
This patch expands on the suggestion in
ben-manes#110 (comment)

Instead of the proposed numeric code the name of factory is used as the
classname to instantiate using reflection.
This reduces the class size with 21K bringing the jar size to 786K.
  • Loading branch information
jvassev committed Nov 2, 2017
1 parent bd15301 commit 4038be5
Showing 1 changed file with 14 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
package com.github.benmanes.caffeine.cache;

import java.lang.reflect.Constructor;
import java.util.Set;

import com.squareup.javapoet.CodeBlock;
Expand Down Expand Up @@ -88,16 +89,18 @@ private LocalCacheSelectorCode expires() {
return this;
}

private LocalCacheSelectorCode selector(Set<String> classNames) {
CodeBlock.Builder switchBuilder = CodeBlock.builder();
switchBuilder.beginControlFlow("switch (sb.toString())");
for (String className : classNames) {
switchBuilder.addStatement(
"case $S: return new $N<>(builder, cacheLoader, async)", className, className);
}
switchBuilder.addStatement("default: throw new $T(sb.toString())", IllegalStateException.class);
switchBuilder.endControlFlow();
block.add(switchBuilder.build());
private LocalCacheSelectorCode selector() {
CodeBlock.Builder reflectBuilder = CodeBlock.builder();
reflectBuilder.add("try {\n"
+ " Class<?> cls = LocalCacheFactory.class.getClassLoader()\n"
+ " .loadClass(\"com.github.benmanes.caffeine.cache.LocalCacheFactory$$\" + sb.toString());\n"
+ " $T<?> ctor = cls.getDeclaredConstructor(Caffeine.class, CacheLoader.class, boolean.class);\n"
+ " return (BoundedLocalCache<K, V>) ctor.newInstance(builder, cacheLoader, async);\n"
+ "} catch (ReflectiveOperationException e) {\n"
+ " throw new IllegalStateException(sb.toString());\n"
+ "}\n"
+ "\n", Constructor.class);
block.add(reflectBuilder.build());
return this;
}

Expand All @@ -113,7 +116,7 @@ public static CodeBlock get(Set<String> classNames) {
.stats()
.maximum()
.expires()
.selector(classNames)
.selector()
.build();
}
}

0 comments on commit 4038be5

Please sign in to comment.