From cd5ca6e20267f86c48ddfc1c34d03ad6f53e02c5 Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Mon, 25 Apr 2016 09:35:46 +0200 Subject: [PATCH] Added more explicit error message for illegal static field assignments. --- .../implementation/LoadedTypeInitializer.java | 8 +++++++- .../LoadedTypeInitializerForStaticFieldTest.java | 11 +++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/LoadedTypeInitializer.java b/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/LoadedTypeInitializer.java index d729f8d328a..1f17f3b129c 100644 --- a/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/LoadedTypeInitializer.java +++ b/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/LoadedTypeInitializer.java @@ -102,7 +102,13 @@ public void onLoad(Class type) { if (!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) { AccessController.doPrivileged(AccessAction.of(field)); } - field.set(STATIC_FIELD, value); + try { + field.set(STATIC_FIELD, value); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException("cannot assign runtime type " + + value.getClass() + " (" + value.getClass().getClassLoader() + ")" + + " to " + field.getType() + " (" + field.getType().getClassLoader() + ")", exception); + } } catch (IllegalAccessException exception) { throw new IllegalArgumentException("Cannot access " + fieldName + " from " + type, exception); } catch (NoSuchFieldException exception) { diff --git a/byte-buddy-dep/src/test/java/net/bytebuddy/implementation/LoadedTypeInitializerForStaticFieldTest.java b/byte-buddy-dep/src/test/java/net/bytebuddy/implementation/LoadedTypeInitializerForStaticFieldTest.java index 112cbeef19b..45bc6a38d05 100644 --- a/byte-buddy-dep/src/test/java/net/bytebuddy/implementation/LoadedTypeInitializerForStaticFieldTest.java +++ b/byte-buddy-dep/src/test/java/net/bytebuddy/implementation/LoadedTypeInitializerForStaticFieldTest.java @@ -37,6 +37,11 @@ public void testNonAccessibleType() throws Exception { assertThat(Qux.foo, is(object)); } + @Test(expected = IllegalStateException.class) + public void testNonAssignableField() throws Exception { + new LoadedTypeInitializer.ForStaticField(FOO, new Object()).onLoad(FooBar.class); + } + @Test public void testObjectProperties() throws Exception { ObjectPropertyAssertion.of(LoadedTypeInitializer.ForStaticField.class).apply(); @@ -65,4 +70,10 @@ private static class Baz { String foo, bar; } + + @SuppressWarnings("unused") + public static class FooBar { + + public static String foo; + } }