Skip to content

Commit

Permalink
Simplified API, better names for methods.
Browse files Browse the repository at this point in the history
  • Loading branch information
raphw committed Jul 28, 2016
1 parent 8c4f759 commit 597813a
Show file tree
Hide file tree
Showing 15 changed files with 98 additions and 99 deletions.
2 changes: 1 addition & 1 deletion byte-buddy-android-test/pom.xml
Expand Up @@ -8,7 +8,7 @@
<groupId>net.bytebuddy</groupId> <groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy-parent</artifactId> <artifactId>byte-buddy-parent</artifactId>
<!-- The version number is not updated by the release plugin as this artifact is not released! --> <!-- The version number is not updated by the release plugin as this artifact is not released! -->
<version>1.4.12-SNAPSHOT</version> <version>1.4.16-SNAPSHOT</version>
</parent> </parent>


<artifactId>byte-buddy-android-test</artifactId> <artifactId>byte-buddy-android-test</artifactId>
Expand Down
Expand Up @@ -46,7 +46,7 @@ public void onCreate(Bundle savedInstanceState) {
public void onClick(View view) { public void onClick(View view) {
ByteBuddy byteBuddy; ByteBuddy byteBuddy;
try { try {
byteBuddy = new ByteBuddy(ClassFileVersion.JAVA_V6); byteBuddy = new ByteBuddy();
} catch (Throwable e) { } catch (Throwable e) {
Log.w(BYTE_BUDDY_TAG, e); Log.w(BYTE_BUDDY_TAG, e);
Toast.makeText(TestActivity.this, "Failure: Could not create Byte Buddy instance. (" + e.getMessage() + ")", Toast.LENGTH_LONG).show(); Toast.makeText(TestActivity.this, "Failure: Could not create Byte Buddy instance. (" + e.getMessage() + ")", Toast.LENGTH_LONG).show();
Expand Down
4 changes: 2 additions & 2 deletions byte-buddy-dep/src/main/java/net/bytebuddy/ByteBuddy.java
Expand Up @@ -146,10 +146,10 @@ public class ByteBuddy {
* is not possible, class files are created Java 6-compatible. * is not possible, class files are created Java 6-compatible.
* </p> * </p>
* *
* @see ClassFileVersion#forCurrentJavaVersion(ClassFileVersion) * @see ClassFileVersion#forThisVm(ClassFileVersion)
*/ */
public ByteBuddy() { public ByteBuddy() {
this(ClassFileVersion.forCurrentJavaVersion(ClassFileVersion.JAVA_V6)); this(ClassFileVersion.forThisVm(ClassFileVersion.JAVA_V6));
} }


/** /**
Expand Down
14 changes: 7 additions & 7 deletions byte-buddy-dep/src/main/java/net/bytebuddy/ClassFileVersion.java
Expand Up @@ -156,8 +156,8 @@ public static ClassFileVersion ofJavaVersion(int javaVersion) {
* *
* @return The currently running Java process's class file version. * @return The currently running Java process's class file version.
*/ */
public static ClassFileVersion forCurrentJavaVersion() { public static ClassFileVersion forThisVm() {
return VERSION_LOCATOR.findCurrentVersion(); return VERSION_LOCATOR.locate();
} }


/** /**
Expand All @@ -169,9 +169,9 @@ public static ClassFileVersion forCurrentJavaVersion() {
* @return The currently running Java process's class file version or the fallback if locating this version is impossible. * @return The currently running Java process's class file version or the fallback if locating this version is impossible.
*/ */
@SuppressFBWarnings(value = "REC_CATCH_EXCEPTION", justification = "Exception should not be rethrown but trigger a fallback") @SuppressFBWarnings(value = "REC_CATCH_EXCEPTION", justification = "Exception should not be rethrown but trigger a fallback")
public static ClassFileVersion forCurrentJavaVersion(ClassFileVersion fallback) { public static ClassFileVersion forThisVm(ClassFileVersion fallback) {
try { try {
return forCurrentJavaVersion(); return forThisVm();
} catch (Exception ignored) { } catch (Exception ignored) {
return fallback; return fallback;
} }
Expand Down Expand Up @@ -304,7 +304,7 @@ protected interface VersionLocator {
* *
* @return The current VM's major version number. * @return The current VM's major version number.
*/ */
ClassFileVersion findCurrentVersion(); ClassFileVersion locate();


/** /**
* A version locator for a JVM of at least version 9. * A version locator for a JVM of at least version 9.
Expand Down Expand Up @@ -338,7 +338,7 @@ protected ForJava9CapableVm(Method current, Method major) {
} }


@Override @Override
public ClassFileVersion findCurrentVersion() { public ClassFileVersion locate() {
try { try {
return ClassFileVersion.ofJavaVersion((Integer) major.invoke(current.invoke(STATIC_METHOD))); return ClassFileVersion.ofJavaVersion((Integer) major.invoke(current.invoke(STATIC_METHOD)));
} catch (InvocationTargetException exception) { } catch (InvocationTargetException exception) {
Expand Down Expand Up @@ -388,7 +388,7 @@ enum ForLegacyVm implements VersionLocator, PrivilegedAction<String> {
private static final String JAVA_VERSION_PROPERTY = "java.version"; private static final String JAVA_VERSION_PROPERTY = "java.version";


@Override @Override
public ClassFileVersion findCurrentVersion() { public ClassFileVersion locate() {
String versionString = AccessController.doPrivileged(this); String versionString = AccessController.doPrivileged(this);
int[] versionIndex = {-1, 0, 0}; int[] versionIndex = {-1, 0, 0};
for (int i = 1; i < 3; i++) { for (int i = 1; i < 3; i++) {
Expand Down
Expand Up @@ -1031,11 +1031,9 @@ public int hashCode() {


@Override @Override
public String toString() { public String toString() {
StringBuilder stringBuilder = new StringBuilder().append(componentType == Class.class ? PropertyDispatcher.TypeRenderer.CURRENT.adjust('[') : '['); return componentType == Class.class
for (AnnotationValue.Loaded<?> value : values) { ? PropertyDispatcher.TypeRenderer.CURRENT.render(values.toArray(new Object[values.size()]))
stringBuilder.append(value.toString()); : Arrays.toString(values.toArray(new Object[values.size()]));
}
return stringBuilder.append(componentType == Class.class ? PropertyDispatcher.TypeRenderer.CURRENT.adjust(']') : ']').toString();
} }
} }
} }
Expand Down
Expand Up @@ -233,7 +233,7 @@ public <T> T conditionalClone(T value) {
TYPE_LOADED { TYPE_LOADED {
@Override @Override
public String toString(Object value) { public String toString(Object value) {
return TypeRenderer.CURRENT.render((Class<?>) value); return TypeRenderer.CURRENT.render(value);
} }


@Override @Override
Expand All @@ -258,17 +258,7 @@ public <T> T conditionalClone(T value) {
TYPE_LOADED_ARRAY { TYPE_LOADED_ARRAY {
@Override @Override
public String toString(Object value) { public String toString(Object value) {
StringBuilder stringBuilder = new StringBuilder().append(TypeRenderer.CURRENT.adjust('[')); return TypeRenderer.CURRENT.render((Object[]) value);
boolean initial = true;
for (Class<?> type : (Class<?>[]) value) {
stringBuilder.append(TypeRenderer.CURRENT.render(type));
if (initial) {
initial = false;
} else {
stringBuilder.append(", ");
}
}
return stringBuilder.append(TypeRenderer.CURRENT.adjust(']')).toString();
} }


@Override @Override
Expand All @@ -295,7 +285,7 @@ public <T> T conditionalClone(T value) {
TYPE_DESCRIBED { TYPE_DESCRIBED {
@Override @Override
public String toString(Object value) { public String toString(Object value) {
return TypeRenderer.CURRENT.render((TypeDescription) value); return TypeRenderer.CURRENT.render(value);
} }


@Override @Override
Expand All @@ -320,17 +310,7 @@ public <T> T conditionalClone(T value) {
TYPE_DESCRIBED_ARRAY { TYPE_DESCRIBED_ARRAY {
@Override @Override
public String toString(Object value) { public String toString(Object value) {
StringBuilder stringBuilder = new StringBuilder().append(TypeRenderer.CURRENT.adjust('[')); return TypeRenderer.CURRENT.render((Object[]) value);
boolean initial = true;
for (TypeDescription typeDescription : (TypeDescription[]) value) {
stringBuilder.append(TypeRenderer.CURRENT.render(typeDescription));
if (initial) {
initial = false;
} else {
stringBuilder.append(", ");
}
}
return stringBuilder.append(TypeRenderer.CURRENT.adjust(']')).toString();
} }


@Override @Override
Expand Down Expand Up @@ -501,30 +481,51 @@ public enum TypeRenderer {
/** /**
* A type renderer for a legacy VM prior to Java 8. * A type renderer for a legacy VM prior to Java 8.
*/ */
FOR_LEGACY_VM(0) { FOR_LEGACY_VM {
@Override @Override
protected String render(Class<?> type) { public String render(Object type) {
if (!(type instanceof Class || type instanceof TypeDescription)) {
throw new IllegalArgumentException("Unexpected type description: " + type);
}
return type.toString(); return type.toString();
} }


@Override @Override
protected String render(TypeDescription typeDescription) { public String render(Object[] type) {
return typeDescription.toString(); return Arrays.toString(type);
} }
}, },


/** /**
* A type renderer for a VM of at least Java version 9. * A type renderer for a VM of at least Java version 9.
*/ */
FOR_JAVA9_CAPABLE_VM('{' - '[') { FOR_JAVA9_CAPABLE_VM {
@Override @Override
protected String render(Class<?> type) { public String render(Object type) {
return type.getName() + JAVA9_NAME_SUFFIX; String name;
if (type instanceof Class) {
name = ((Class<?>) type).getName();
} else if (type instanceof TypeDescription) {
name = ((TypeDescription) type).getName();
} else {
throw new IllegalArgumentException("Unexpected type description: " + type);
}
return name + JAVA9_NAME_SUFFIX;
} }


@Override @Override
protected String render(TypeDescription typeDescription) { public String render(Object[] type) {
return typeDescription.getName() + JAVA9_NAME_SUFFIX; StringBuilder stringBuilder = new StringBuilder().append('{');
boolean initial = true;
for (Object aType : type) {
stringBuilder.append(render(aType));
if (initial) {
initial = false;
} else {
stringBuilder.append(", ");
}
}
return stringBuilder.append('}').toString();
} }
}; };


Expand All @@ -544,50 +545,26 @@ protected String render(TypeDescription typeDescription) {
* @return The type renderer to be used on the current VM. * @return The type renderer to be used on the current VM.
*/ */
private static TypeRenderer make() { private static TypeRenderer make() {
return ClassFileVersion.forCurrentJavaVersion(ClassFileVersion.JAVA_V6).isAtLeast(ClassFileVersion.JAVA_V9) return ClassFileVersion.forThisVm(ClassFileVersion.JAVA_V6).isAtLeast(ClassFileVersion.JAVA_V9)
? FOR_JAVA9_CAPABLE_VM ? FOR_JAVA9_CAPABLE_VM
: FOR_LEGACY_VM; : FOR_LEGACY_VM;
} }


/** /**
* The offset to add for braces starting from {@code [} or {@code ]}. * Renders a {@link Class} or {@link TypeDescription} constant.
*/
private final int offset;

/**
* Creates a new type renderer.
*
* @param offset The offset to add for braces.
*/
TypeRenderer(int offset) {
this.offset = offset;
}

/**
* Adjusts a brace character.
*
* @param delimiter The delimiter being used.
* @return The adjusted delimiter.
*/
public char adjust(char delimiter) {
return (char) (delimiter + offset);
}

/**
* Renders a {@link Class} constant.
* *
* @param type The type to be rendered. * @param type The type to be rendered.
* @return The rendered string. * @return The rendered string.
*/ */
protected abstract String render(Class<?> type); public abstract String render(Object type);


/** /**
* Renders a {@link TypeDescription} which represents a constant. * Renders an array of {@link Class} or {@link TypeDescription} constants.
* *
* @param typeDescription The type to be rendered. * @param type The types to be rendered.
* @return The rendered string. * @return The rendered string.
*/ */
protected abstract String render(TypeDescription typeDescription); public abstract String render(Object[] type);


@Override @Override
public String toString() { public String toString() {
Expand Down
Expand Up @@ -104,7 +104,7 @@ public void testLessThanJava8() throws Exception {
@Test @Test
public void testSimpleClassCreation() throws Exception { public void testSimpleClassCreation() throws Exception {
ClassFileVersion classFileVersion = ClassFileVersion.ofJavaVersion(javaVersion); ClassFileVersion classFileVersion = ClassFileVersion.ofJavaVersion(javaVersion);
if (ClassFileVersion.forCurrentJavaVersion().compareTo(classFileVersion) >= 0) { if (ClassFileVersion.forThisVm().compareTo(classFileVersion) >= 0) {
Class<?> type = new ByteBuddy(classFileVersion) Class<?> type = new ByteBuddy(classFileVersion)
.subclass(Foo.class) .subclass(Foo.class)
.make() .make()
Expand Down
Expand Up @@ -40,7 +40,7 @@ public void testVersionPropertyAction() throws Exception {


@Test @Test
public void testVersionOfClass() throws Exception { public void testVersionOfClass() throws Exception {
assertThat(ClassFileVersion.of(Foo.class).compareTo(ClassFileVersion.forCurrentJavaVersion()) < 1, is(true)); assertThat(ClassFileVersion.of(Foo.class).compareTo(ClassFileVersion.forThisVm()) < 1, is(true));
} }


@Test @Test
Expand Down
Expand Up @@ -78,7 +78,7 @@ public void testLoading() throws Exception {
assertThat(type, not(CoreMatchers.<Class<?>>is(Foo.class))); assertThat(type, not(CoreMatchers.<Class<?>>is(Foo.class)));
assertThat(type.getPackage(), notNullValue(Package.class)); assertThat(type.getPackage(), notNullValue(Package.class));
// Due to change in API in Java 9 where package identity is no longer bound by hierarchy. // Due to change in API in Java 9 where package identity is no longer bound by hierarchy.
assertThat(type.getPackage(), ClassFileVersion.forCurrentJavaVersion().isAtLeast(ClassFileVersion.JAVA_V9) assertThat(type.getPackage(), ClassFileVersion.forThisVm().isAtLeast(ClassFileVersion.JAVA_V9)
? not(is(Foo.class.getPackage())) ? not(is(Foo.class.getPackage()))
: is(Foo.class.getPackage())); : is(Foo.class.getPackage()));
} }
Expand Down
Expand Up @@ -166,7 +166,7 @@ public void testMultipleTypeArgumentAnnotation() throws Exception {
private Class<?> makeTypeWithAnnotation(Annotation annotation) throws Exception { private Class<?> makeTypeWithAnnotation(Annotation annotation) throws Exception {
when(valueFilter.isRelevant(any(AnnotationDescription.class), any(MethodDescription.InDefinedShape.class))).thenReturn(true); when(valueFilter.isRelevant(any(AnnotationDescription.class), any(MethodDescription.InDefinedShape.class))).thenReturn(true);
ClassWriter classWriter = new ClassWriter(AsmVisitorWrapper.NO_FLAGS); ClassWriter classWriter = new ClassWriter(AsmVisitorWrapper.NO_FLAGS);
classWriter.visit(ClassFileVersion.forCurrentJavaVersion().getMinorMajorVersion(), classWriter.visit(ClassFileVersion.forThisVm().getMinorMajorVersion(),
Opcodes.ACC_PUBLIC, Opcodes.ACC_PUBLIC,
BAR.replace('.', '/'), BAR.replace('.', '/'),
null, null,
Expand All @@ -190,7 +190,7 @@ private Class<?> makeTypeWithAnnotation(Annotation annotation) throws Exception
private Class<?> makeTypeWithSuperClassAnnotation(Annotation annotation) throws Exception { private Class<?> makeTypeWithSuperClassAnnotation(Annotation annotation) throws Exception {
when(valueFilter.isRelevant(any(AnnotationDescription.class), any(MethodDescription.InDefinedShape.class))).thenReturn(true); when(valueFilter.isRelevant(any(AnnotationDescription.class), any(MethodDescription.InDefinedShape.class))).thenReturn(true);
ClassWriter classWriter = new ClassWriter(AsmVisitorWrapper.NO_FLAGS); ClassWriter classWriter = new ClassWriter(AsmVisitorWrapper.NO_FLAGS);
classWriter.visit(ClassFileVersion.forCurrentJavaVersion().getMinorMajorVersion(), classWriter.visit(ClassFileVersion.forThisVm().getMinorMajorVersion(),
Opcodes.ACC_PUBLIC, Opcodes.ACC_PUBLIC,
BAR.replace('.', '/'), BAR.replace('.', '/'),
null, null,
Expand Down
Expand Up @@ -40,7 +40,7 @@ protected Class<?> proxyOnlyDeclaredMethodOf(Class<?> proxyTarget) throws Except
when(methodAccessorFactory.registerAccessorFor(eq(specialMethodInvocation))).thenReturn(proxyMethod); when(methodAccessorFactory.registerAccessorFor(eq(specialMethodInvocation))).thenReturn(proxyMethod);
String auxiliaryTypeName = getClass().getName() + "$" + proxyTarget.getSimpleName() + "$Proxy"; String auxiliaryTypeName = getClass().getName() + "$" + proxyTarget.getSimpleName() + "$Proxy";
DynamicType dynamicType = new MethodCallProxy(specialMethodInvocation, false).make(auxiliaryTypeName, DynamicType dynamicType = new MethodCallProxy(specialMethodInvocation, false).make(auxiliaryTypeName,
ClassFileVersion.forCurrentJavaVersion(), ClassFileVersion.forThisVm(),
methodAccessorFactory); methodAccessorFactory);
DynamicType.Unloaded<?> unloaded = (DynamicType.Unloaded<?>) dynamicType; DynamicType.Unloaded<?> unloaded = (DynamicType.Unloaded<?>) dynamicType;
Class<?> auxiliaryType = unloaded.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded(); Class<?> auxiliaryType = unloaded.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded();
Expand Down
Expand Up @@ -88,7 +88,7 @@ public void testAllIllegal() throws Exception {
invocationFactory, invocationFactory,
true, true,
false) false)
.make(BAR, ClassFileVersion.forCurrentJavaVersion(), methodAccessorFactory) .make(BAR, ClassFileVersion.forThisVm(), methodAccessorFactory)
.getTypeDescription(); .getTypeDescription();
assertThat(dynamicType.getModifiers(), is(modifiers)); assertThat(dynamicType.getModifiers(), is(modifiers));
assertThat(dynamicType.getSuperClass().asErasure(), is(foo)); assertThat(dynamicType.getSuperClass().asErasure(), is(foo));
Expand Down Expand Up @@ -119,7 +119,7 @@ public void testAllLegal() throws Exception {
invocationFactory, invocationFactory,
true, true,
false) false)
.make(BAR, ClassFileVersion.forCurrentJavaVersion(), methodAccessorFactory) .make(BAR, ClassFileVersion.forThisVm(), methodAccessorFactory)
.getTypeDescription(); .getTypeDescription();
assertThat(dynamicType.getModifiers(), is(modifiers)); assertThat(dynamicType.getModifiers(), is(modifiers));
assertThat(dynamicType.getSuperClass().asErasure(), is(foo)); assertThat(dynamicType.getSuperClass().asErasure(), is(foo));
Expand Down Expand Up @@ -150,7 +150,7 @@ public void testAllLegalSerializable() throws Exception {
invocationFactory, invocationFactory,
true, true,
true) true)
.make(BAR, ClassFileVersion.forCurrentJavaVersion(), methodAccessorFactory) .make(BAR, ClassFileVersion.forThisVm(), methodAccessorFactory)
.getTypeDescription(); .getTypeDescription();
assertThat(dynamicType.getModifiers(), is(modifiers)); assertThat(dynamicType.getModifiers(), is(modifiers));
assertThat(dynamicType.getSuperClass().asErasure(), is(foo)); assertThat(dynamicType.getSuperClass().asErasure(), is(foo));
Expand Down Expand Up @@ -181,7 +181,7 @@ public void testAllLegalNotIgnoreFinalizer() throws Exception {
invocationFactory, invocationFactory,
false, false,
false) false)
.make(BAR, ClassFileVersion.forCurrentJavaVersion(), methodAccessorFactory) .make(BAR, ClassFileVersion.forThisVm(), methodAccessorFactory)
.getTypeDescription(); .getTypeDescription();
assertThat(dynamicType.getModifiers(), is(modifiers)); assertThat(dynamicType.getModifiers(), is(modifiers));
assertThat(dynamicType.getSuperClass().asErasure(), is(foo)); assertThat(dynamicType.getSuperClass().asErasure(), is(foo));
Expand Down
Expand Up @@ -19,7 +19,7 @@ public class JavaVersionRule implements MethodRule {
private final boolean hotSpot; private final boolean hotSpot;


public JavaVersionRule() { public JavaVersionRule() {
currentVersion = ClassFileVersion.forCurrentJavaVersion(); currentVersion = ClassFileVersion.forThisVm();
hotSpot = System.getProperty("java.vm.name", "").toLowerCase(Locale.US).contains("hotspot"); hotSpot = System.getProperty("java.vm.name", "").toLowerCase(Locale.US).contains("hotspot");
} }


Expand Down

0 comments on commit 597813a

Please sign in to comment.