target
stringlengths
20
113k
src_fm
stringlengths
11
86.3k
src_fm_fc
stringlengths
21
86.4k
src_fm_fc_co
stringlengths
30
86.4k
src_fm_fc_ms
stringlengths
42
86.8k
src_fm_fc_ms_ff
stringlengths
43
86.8k
@Test public void findingDeclaredConstructorQuietlyWhenNoSuchConstructor() { thrown.expect(ReflectionException.class); thrown.expectMessage(NoSuchMethodException.class.getName()); assertNull(findDeclaredConstructor(Integer.class, Object.class)); }
public static <T> Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes) { try { Constructor<T> ctor = type.getDeclaredConstructor(parameterTypes); ctor.setAccessible(true); return ctor; } catch (Exception ex) { throw reflectionException(ex); } }
Reflection { public static <T> Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes) { try { Constructor<T> ctor = type.getDeclaredConstructor(parameterTypes); ctor.setAccessible(true); return ctor; } catch (Exception ex) { throw reflectionException(ex); } } }
Reflection { public static <T> Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes) { try { Constructor<T> ctor = type.getDeclaredConstructor(parameterTypes); ctor.setAccessible(true); return ctor; } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); }
Reflection { public static <T> Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes) { try { Constructor<T> ctor = type.getDeclaredConstructor(parameterTypes); ctor.setAccessible(true); return ctor; } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static <T> Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes) { try { Constructor<T> ctor = type.getDeclaredConstructor(parameterTypes); ctor.setAccessible(true); return ctor; } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void versusCharsetThatDoesNotSupportEncoding() { Charset noEncoding; try { noEncoding = Charset.forName("ISO-2022-CN"); } catch (UnsupportedCharsetException testNotValid) { return; } thrown.expect(IllegalArgumentException.class); CodePoints.forCharset(noEncoding); }
public static CodePoints forCharset(Charset c) { if (ENCODABLES.containsKey(c)) return ENCODABLES.get(c); CodePoints points = load(c); ENCODABLES.put(c, points); return points; }
CodePoints { public static CodePoints forCharset(Charset c) { if (ENCODABLES.containsKey(c)) return ENCODABLES.get(c); CodePoints points = load(c); ENCODABLES.put(c, points); return points; } }
CodePoints { public static CodePoints forCharset(Charset c) { if (ENCODABLES.containsKey(c)) return ENCODABLES.get(c); CodePoints points = load(c); ENCODABLES.put(c, points); return points; } CodePoints(); }
CodePoints { public static CodePoints forCharset(Charset c) { if (ENCODABLES.containsKey(c)) return ENCODABLES.get(c); CodePoints points = load(c); ENCODABLES.put(c, points); return points; } CodePoints(); int at(int index); int size(); boolean contains(int codePoint); static CodePoints forCharset(Charset c); }
CodePoints { public static CodePoints forCharset(Charset c) { if (ENCODABLES.containsKey(c)) return ENCODABLES.get(c); CodePoints points = load(c); ENCODABLES.put(c, points); return points; } CodePoints(); int at(int index); int size(); boolean contains(int codePoint); static CodePoints forCharset(Charset c); }
@Test public void findingSingleAccessibleConstructorSuccessfully() { Constructor<Object> ctor = singleAccessibleConstructor(Object.class); assertEquals(0, ctor.getParameterTypes().length); }
@SuppressWarnings("unchecked") public static <T> Constructor<T> singleAccessibleConstructor( Class<T> type) { Constructor<?>[] constructors = type.getConstructors(); if (constructors.length != 1) { throw new ReflectionException( type + " needs a single accessible constructor"); } return (Constructor<T>) constructors[0]; }
Reflection { @SuppressWarnings("unchecked") public static <T> Constructor<T> singleAccessibleConstructor( Class<T> type) { Constructor<?>[] constructors = type.getConstructors(); if (constructors.length != 1) { throw new ReflectionException( type + " needs a single accessible constructor"); } return (Constructor<T>) constructors[0]; } }
Reflection { @SuppressWarnings("unchecked") public static <T> Constructor<T> singleAccessibleConstructor( Class<T> type) { Constructor<?>[] constructors = type.getConstructors(); if (constructors.length != 1) { throw new ReflectionException( type + " needs a single accessible constructor"); } return (Constructor<T>) constructors[0]; } private Reflection(); }
Reflection { @SuppressWarnings("unchecked") public static <T> Constructor<T> singleAccessibleConstructor( Class<T> type) { Constructor<?>[] constructors = type.getConstructors(); if (constructors.length != 1) { throw new ReflectionException( type + " needs a single accessible constructor"); } return (Constructor<T>) constructors[0]; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { @SuppressWarnings("unchecked") public static <T> Constructor<T> singleAccessibleConstructor( Class<T> type) { Constructor<?>[] constructors = type.getConstructors(); if (constructors.length != 1) { throw new ReflectionException( type + " needs a single accessible constructor"); } return (Constructor<T>) constructors[0]; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void rejectsFindingSingleAccessibleConstructorOnNonConformingClass() { thrown.expect(ReflectionException.class); thrown.expectMessage(Integer.class + " needs a single accessible constructor"); singleAccessibleConstructor(Integer.class); }
@SuppressWarnings("unchecked") public static <T> Constructor<T> singleAccessibleConstructor( Class<T> type) { Constructor<?>[] constructors = type.getConstructors(); if (constructors.length != 1) { throw new ReflectionException( type + " needs a single accessible constructor"); } return (Constructor<T>) constructors[0]; }
Reflection { @SuppressWarnings("unchecked") public static <T> Constructor<T> singleAccessibleConstructor( Class<T> type) { Constructor<?>[] constructors = type.getConstructors(); if (constructors.length != 1) { throw new ReflectionException( type + " needs a single accessible constructor"); } return (Constructor<T>) constructors[0]; } }
Reflection { @SuppressWarnings("unchecked") public static <T> Constructor<T> singleAccessibleConstructor( Class<T> type) { Constructor<?>[] constructors = type.getConstructors(); if (constructors.length != 1) { throw new ReflectionException( type + " needs a single accessible constructor"); } return (Constructor<T>) constructors[0]; } private Reflection(); }
Reflection { @SuppressWarnings("unchecked") public static <T> Constructor<T> singleAccessibleConstructor( Class<T> type) { Constructor<?>[] constructors = type.getConstructors(); if (constructors.length != 1) { throw new ReflectionException( type + " needs a single accessible constructor"); } return (Constructor<T>) constructors[0]; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { @SuppressWarnings("unchecked") public static <T> Constructor<T> singleAccessibleConstructor( Class<T> type) { Constructor<?>[] constructors = type.getConstructors(); if (constructors.length != 1) { throw new ReflectionException( type + " needs a single accessible constructor"); } return (Constructor<T>) constructors[0]; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void invokingZeroArgConstructorQuietlyWrapsInstantiationException() { thrown.expect(ReflectionException.class); thrown.expectMessage(InstantiationException.class.getName()); instantiate(ZeroArgInstantiationProblematic.class); }
public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void invokingZeroArgConstructorQuietlyWrapsIllegalAccessException() { thrown.expect(ReflectionException.class); thrown.expectMessage(IllegalAccessException.class.getName()); instantiate(ZeroArgIllegalAccessProblematic.class); }
public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void invokingZeroArgConstructorPropagatesExceptionsRaisedByConstructor() { thrown.expect(IllegalStateException.class); instantiate(InvocationTargetProblematic.class); }
public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void invokingNonZeroArgConstructorQuietlyWrapsInstantiationException() throws Exception { thrown.expect(ReflectionException.class); thrown.expectMessage(InstantiationException.class.getName()); instantiate(MultiArgInstantiationProblematic.class.getConstructor(int.class), 2); }
public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void invokingNonZeroArgConstructorQuietlyWrapsIllegalAccessException() throws Exception { thrown.expect(ReflectionException.class); thrown.expectMessage(IllegalAccessException.class.getName()); instantiate(MultiArgIllegalAccessProblematic.class.getDeclaredConstructor(int.class), 2); }
public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void invokingNonZeroArgConstructorQuietlyPropagatesIllegalArgumentException() throws Exception { thrown.expect(IllegalArgumentException.class); instantiate(Integer.class.getDeclaredConstructor(int.class), "2"); }
public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void invokingNonZeroArgConstructorWrapsExceptionsRaisedByConstructor() throws Exception { thrown.expect(ReflectionException.class); thrown.expectMessage(IndexOutOfBoundsException.class.getName()); instantiate(InvocationTargetProblematic.class.getConstructor(int.class), 2); }
public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void findingNonExistentMethodQuietlyWrapsNoSuchMethodException() { thrown.expect(ReflectionException.class); thrown.expectMessage(NoSuchMethodException.class.getName()); findMethod(getClass(), "foo"); }
public static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes) { try { return target.getMethod(methodName, argTypes); } catch (Exception ex) { throw reflectionException(ex); } }
Reflection { public static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes) { try { return target.getMethod(methodName, argTypes); } catch (Exception ex) { throw reflectionException(ex); } } }
Reflection { public static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes) { try { return target.getMethod(methodName, argTypes); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); }
Reflection { public static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes) { try { return target.getMethod(methodName, argTypes); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes) { try { return target.getMethod(methodName, argTypes); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void lowIndex() { thrown.expect(IndexOutOfBoundsException.class); new CodePoints().at(-1); }
public int at(int index) { if (index < 0) throw new IndexOutOfBoundsException("illegal negative index: " + index); int min = 0; int max = ranges.size() - 1; while (min <= max) { int midpoint = min + ((max - min) / 2); CodePointRange current = ranges.get(midpoint); if (index >= current.previousCount && index < current.previousCount + current.size()) return current.low + index - current.previousCount; else if (index < current.previousCount) max = midpoint - 1; else min = midpoint + 1; } throw new IndexOutOfBoundsException(String.valueOf(index)); }
CodePoints { public int at(int index) { if (index < 0) throw new IndexOutOfBoundsException("illegal negative index: " + index); int min = 0; int max = ranges.size() - 1; while (min <= max) { int midpoint = min + ((max - min) / 2); CodePointRange current = ranges.get(midpoint); if (index >= current.previousCount && index < current.previousCount + current.size()) return current.low + index - current.previousCount; else if (index < current.previousCount) max = midpoint - 1; else min = midpoint + 1; } throw new IndexOutOfBoundsException(String.valueOf(index)); } }
CodePoints { public int at(int index) { if (index < 0) throw new IndexOutOfBoundsException("illegal negative index: " + index); int min = 0; int max = ranges.size() - 1; while (min <= max) { int midpoint = min + ((max - min) / 2); CodePointRange current = ranges.get(midpoint); if (index >= current.previousCount && index < current.previousCount + current.size()) return current.low + index - current.previousCount; else if (index < current.previousCount) max = midpoint - 1; else min = midpoint + 1; } throw new IndexOutOfBoundsException(String.valueOf(index)); } CodePoints(); }
CodePoints { public int at(int index) { if (index < 0) throw new IndexOutOfBoundsException("illegal negative index: " + index); int min = 0; int max = ranges.size() - 1; while (min <= max) { int midpoint = min + ((max - min) / 2); CodePointRange current = ranges.get(midpoint); if (index >= current.previousCount && index < current.previousCount + current.size()) return current.low + index - current.previousCount; else if (index < current.previousCount) max = midpoint - 1; else min = midpoint + 1; } throw new IndexOutOfBoundsException(String.valueOf(index)); } CodePoints(); int at(int index); int size(); boolean contains(int codePoint); static CodePoints forCharset(Charset c); }
CodePoints { public int at(int index) { if (index < 0) throw new IndexOutOfBoundsException("illegal negative index: " + index); int min = 0; int max = ranges.size() - 1; while (min <= max) { int midpoint = min + ((max - min) / 2); CodePointRange current = ranges.get(midpoint); if (index >= current.previousCount && index < current.previousCount + current.size()) return current.low + index - current.previousCount; else if (index < current.previousCount) max = midpoint - 1; else min = midpoint + 1; } throw new IndexOutOfBoundsException(String.valueOf(index)); } CodePoints(); int at(int index); int size(); boolean contains(int codePoint); static CodePoints forCharset(Charset c); }
@Test public void invokingMethodQuietlyWrapsIllegalAccessException() throws Exception { Method method = ZeroArgIllegalAccessProblematic.class.getDeclaredMethod("foo"); thrown.expect(ReflectionException.class); thrown.expectMessage(IllegalAccessException.class.getName()); invoke(method, new ZeroArgIllegalAccessProblematic(0)); }
public static Object invoke(Method method, Object target, Object... args) { try { return method.invoke(target, args); } catch (Exception ex) { throw reflectionException(ex); } }
Reflection { public static Object invoke(Method method, Object target, Object... args) { try { return method.invoke(target, args); } catch (Exception ex) { throw reflectionException(ex); } } }
Reflection { public static Object invoke(Method method, Object target, Object... args) { try { return method.invoke(target, args); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); }
Reflection { public static Object invoke(Method method, Object target, Object... args) { try { return method.invoke(target, args); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static Object invoke(Method method, Object target, Object... args) { try { return method.invoke(target, args); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void findingDefaultValueOfAnnotationAttribute() throws Exception { assertEquals("baz", defaultValueOf(Foo.class, "bar")); }
public static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute) { try { return annotationType.getMethod(attribute).getDefaultValue(); } catch (Exception ex) { throw reflectionException(ex); } }
Reflection { public static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute) { try { return annotationType.getMethod(attribute).getDefaultValue(); } catch (Exception ex) { throw reflectionException(ex); } } }
Reflection { public static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute) { try { return annotationType.getMethod(attribute).getDefaultValue(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); }
Reflection { public static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute) { try { return annotationType.getMethod(attribute).getDefaultValue(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute) { try { return annotationType.getMethod(attribute).getDefaultValue(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void missingAnnotationAttribute() throws Exception { thrown.expect(ReflectionException.class); thrown.expectMessage(NoSuchMethodException.class.getName()); defaultValueOf(Foo.class, "noneSuch"); }
public static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute) { try { return annotationType.getMethod(attribute).getDefaultValue(); } catch (Exception ex) { throw reflectionException(ex); } }
Reflection { public static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute) { try { return annotationType.getMethod(attribute).getDefaultValue(); } catch (Exception ex) { throw reflectionException(ex); } } }
Reflection { public static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute) { try { return annotationType.getMethod(attribute).getDefaultValue(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); }
Reflection { public static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute) { try { return annotationType.getMethod(attribute).getDefaultValue(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute) { try { return annotationType.getMethod(attribute).getDefaultValue(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void aClassIsNotASingleAbstractMethodType() { assertNull(singleAbstractMethodOf(String.class)); }
public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void anInterfaceWithNoMethodsIsNotASingleAbstractMethodType() { assertNull(singleAbstractMethodOf(Serializable.class)); }
public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void anInterfaceWithASingleAbstractMethodIsASingleAbstractMethodType() throws Exception { assertEquals( Comparator.class.getMethod("compare", Object.class, Object.class), singleAbstractMethodOf(Comparator.class)); }
public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void anInterfaceThatOverridesEqualsIsNotASingleAbstractMethodType() throws Exception { assertNull(singleAbstractMethodOf(OverridingEquals.class)); }
public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void anInterfaceThatOverloadsEqualsCanBeASingleAbstractMethodType() throws Exception { assertEquals( OverloadingEquals.class.getMethod("equals", String.class), singleAbstractMethodOf(OverloadingEquals.class)); }
public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void anInterfaceThatOverloadsEqualsWithMoreThanOneParameterCanBeASingleAbstractMethodType() throws Exception { assertEquals( OverloadingEqualsWithMoreParameters.class.getMethod("equals", Object.class, Object.class), singleAbstractMethodOf(OverloadingEqualsWithMoreParameters.class)); }
public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void anInterfaceThatOverloadsEqualsWithMixedParameterTypesIsNotASingleAbstractMethodType() throws Exception { assertEquals( OverloadingEqualsWithMixedParameterTypes.class.getMethod("equals", Object.class, String.class, int.class), singleAbstractMethodOf(OverloadingEqualsWithMixedParameterTypes.class)); }
public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void highIndex() { thrown.expect(IndexOutOfBoundsException.class); new CodePoints().at(0); }
public int at(int index) { if (index < 0) throw new IndexOutOfBoundsException("illegal negative index: " + index); int min = 0; int max = ranges.size() - 1; while (min <= max) { int midpoint = min + ((max - min) / 2); CodePointRange current = ranges.get(midpoint); if (index >= current.previousCount && index < current.previousCount + current.size()) return current.low + index - current.previousCount; else if (index < current.previousCount) max = midpoint - 1; else min = midpoint + 1; } throw new IndexOutOfBoundsException(String.valueOf(index)); }
CodePoints { public int at(int index) { if (index < 0) throw new IndexOutOfBoundsException("illegal negative index: " + index); int min = 0; int max = ranges.size() - 1; while (min <= max) { int midpoint = min + ((max - min) / 2); CodePointRange current = ranges.get(midpoint); if (index >= current.previousCount && index < current.previousCount + current.size()) return current.low + index - current.previousCount; else if (index < current.previousCount) max = midpoint - 1; else min = midpoint + 1; } throw new IndexOutOfBoundsException(String.valueOf(index)); } }
CodePoints { public int at(int index) { if (index < 0) throw new IndexOutOfBoundsException("illegal negative index: " + index); int min = 0; int max = ranges.size() - 1; while (min <= max) { int midpoint = min + ((max - min) / 2); CodePointRange current = ranges.get(midpoint); if (index >= current.previousCount && index < current.previousCount + current.size()) return current.low + index - current.previousCount; else if (index < current.previousCount) max = midpoint - 1; else min = midpoint + 1; } throw new IndexOutOfBoundsException(String.valueOf(index)); } CodePoints(); }
CodePoints { public int at(int index) { if (index < 0) throw new IndexOutOfBoundsException("illegal negative index: " + index); int min = 0; int max = ranges.size() - 1; while (min <= max) { int midpoint = min + ((max - min) / 2); CodePointRange current = ranges.get(midpoint); if (index >= current.previousCount && index < current.previousCount + current.size()) return current.low + index - current.previousCount; else if (index < current.previousCount) max = midpoint - 1; else min = midpoint + 1; } throw new IndexOutOfBoundsException(String.valueOf(index)); } CodePoints(); int at(int index); int size(); boolean contains(int codePoint); static CodePoints forCharset(Charset c); }
CodePoints { public int at(int index) { if (index < 0) throw new IndexOutOfBoundsException("illegal negative index: " + index); int min = 0; int max = ranges.size() - 1; while (min <= max) { int midpoint = min + ((max - min) / 2); CodePointRange current = ranges.get(midpoint); if (index >= current.previousCount && index < current.previousCount + current.size()) return current.low + index - current.previousCount; else if (index < current.previousCount) max = midpoint - 1; else min = midpoint + 1; } throw new IndexOutOfBoundsException(String.valueOf(index)); } CodePoints(); int at(int index); int size(); boolean contains(int codePoint); static CodePoints forCharset(Charset c); }
@Test public void anInterfaceThatOverridesHashCodeIsNotASingleAbstractMethodType() throws Exception { assertNull(singleAbstractMethodOf(OverridingHashCode.class)); }
public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void anInterfaceThatOverloadsHashCodeCanBeASingleAbstractMethodType() throws Exception { assertEquals( OverloadingHashCode.class.getMethod("hashCode", Object.class), singleAbstractMethodOf(OverloadingHashCode.class)); }
public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void anInterfaceThatOverridesToStringIsNotASingleAbstractMethodType() throws Exception { assertNull(singleAbstractMethodOf(OverridingToString.class)); }
public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void anInterfaceThatOverloadsToStringCanBeASingleAbstractMethodType() throws Exception { assertEquals( OverloadingToString.class.getMethod("toString", Object.class), singleAbstractMethodOf(OverloadingToString.class)); }
public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void aClassIsNotAMarkerInterface() { assertFalse(isMarkerInterface(Object.class)); }
public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void anInterfaceWithAMethodIsNotAMarkerInterface() { assertFalse(isMarkerInterface(NotAMarker.class)); }
public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void anInterfaceWithNoMethodsButSuperMethodsIsNotAMarkerInterface() { assertFalse(isMarkerInterface(SubNotAMarker.class)); }
public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void anInterfaceThatOverridesEqualsIsAMarkerInterface() { assertTrue(isMarkerInterface(OverridingEquals.class)); }
public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void anInterfaceThatOverloadsEqualsIsNotAMarkerInterface() { assertFalse(isMarkerInterface(OverloadingEquals.class)); }
public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void anInterfaceThatOverloadsEqualsWithMoreThanOneParameterIsNotAMarkerInterface() { assertFalse( isMarkerInterface(OverloadingEqualsWithMoreParameters.class)); }
public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void sizeOfEmpty() { assertEquals(0, new CodePoints().size()); }
public int size() { if (ranges.isEmpty()) return 0; CodePointRange last = ranges.get(ranges.size() - 1); return last.previousCount + last.size(); }
CodePoints { public int size() { if (ranges.isEmpty()) return 0; CodePointRange last = ranges.get(ranges.size() - 1); return last.previousCount + last.size(); } }
CodePoints { public int size() { if (ranges.isEmpty()) return 0; CodePointRange last = ranges.get(ranges.size() - 1); return last.previousCount + last.size(); } CodePoints(); }
CodePoints { public int size() { if (ranges.isEmpty()) return 0; CodePointRange last = ranges.get(ranges.size() - 1); return last.previousCount + last.size(); } CodePoints(); int at(int index); int size(); boolean contains(int codePoint); static CodePoints forCharset(Charset c); }
CodePoints { public int size() { if (ranges.isEmpty()) return 0; CodePointRange last = ranges.get(ranges.size() - 1); return last.previousCount + last.size(); } CodePoints(); int at(int index); int size(); boolean contains(int codePoint); static CodePoints forCharset(Charset c); }
@Test public void anInterfaceThatOverloadsEqualsWithMixedParameterTypesIsNotAMarkerInterface() { assertFalse( isMarkerInterface(OverloadingEqualsWithMixedParameterTypes.class)); }
public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void anInterfaceThatOverridesHashCodeIsAMarkerInterface() { assertTrue(isMarkerInterface(OverridingHashCode.class)); }
public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void anInterfaceThatOverloadsHashCodeIsNotAMarkerInterface() { assertFalse(isMarkerInterface(OverloadingHashCode.class)); }
public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void anInterfaceThatOverridesToStringIsAMarkerInterface() { assertTrue(isMarkerInterface(OverridingToString.class)); }
public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void anInterfaceThatOverloadsToStringIsNotAMarkerInterface() { assertFalse(isMarkerInterface(OverloadingToString.class)); }
public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void anInterfaceWithOnlyDefaultMethodsIsAMarkerInterface() { assertTrue(isMarkerInterface(OnlyDefaultMethods.class)); }
public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void settingFieldWithoutBypassingProtection() throws Exception { WithAccessibleField target = new WithAccessibleField(); setField(target.getClass().getField("i"), target, 2, false); assertEquals(2, target.i); }
public static void setField( Field field, Object target, Object value, boolean suppressProtection) { doPrivileged((PrivilegedAction<Void>) () -> { field.setAccessible(suppressProtection); return null; }); try { field.set(target, value); } catch (Exception ex) { throw reflectionException(ex); } }
Reflection { public static void setField( Field field, Object target, Object value, boolean suppressProtection) { doPrivileged((PrivilegedAction<Void>) () -> { field.setAccessible(suppressProtection); return null; }); try { field.set(target, value); } catch (Exception ex) { throw reflectionException(ex); } } }
Reflection { public static void setField( Field field, Object target, Object value, boolean suppressProtection) { doPrivileged((PrivilegedAction<Void>) () -> { field.setAccessible(suppressProtection); return null; }); try { field.set(target, value); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); }
Reflection { public static void setField( Field field, Object target, Object value, boolean suppressProtection) { doPrivileged((PrivilegedAction<Void>) () -> { field.setAccessible(suppressProtection); return null; }); try { field.set(target, value); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static void setField( Field field, Object target, Object value, boolean suppressProtection) { doPrivileged((PrivilegedAction<Void>) () -> { field.setAccessible(suppressProtection); return null; }); try { field.set(target, value); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void settingInaccessibleFieldBypassingProtection() throws Exception { WithInaccessibleField target = new WithInaccessibleField(); setField(target.getClass().getDeclaredField("i"), target, 3, true); assertEquals(3, target.i); }
public static void setField( Field field, Object target, Object value, boolean suppressProtection) { doPrivileged((PrivilegedAction<Void>) () -> { field.setAccessible(suppressProtection); return null; }); try { field.set(target, value); } catch (Exception ex) { throw reflectionException(ex); } }
Reflection { public static void setField( Field field, Object target, Object value, boolean suppressProtection) { doPrivileged((PrivilegedAction<Void>) () -> { field.setAccessible(suppressProtection); return null; }); try { field.set(target, value); } catch (Exception ex) { throw reflectionException(ex); } } }
Reflection { public static void setField( Field field, Object target, Object value, boolean suppressProtection) { doPrivileged((PrivilegedAction<Void>) () -> { field.setAccessible(suppressProtection); return null; }); try { field.set(target, value); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); }
Reflection { public static void setField( Field field, Object target, Object value, boolean suppressProtection) { doPrivileged((PrivilegedAction<Void>) () -> { field.setAccessible(suppressProtection); return null; }); try { field.set(target, value); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static void setField( Field field, Object target, Object value, boolean suppressProtection) { doPrivileged((PrivilegedAction<Void>) () -> { field.setAccessible(suppressProtection); return null; }); try { field.set(target, value); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void settingInaccessibleFieldWithoutBypassingProtection() throws Exception { WithInaccessibleField target = new WithInaccessibleField(); thrown.expect(ReflectionException.class); thrown.expectMessage(IllegalAccessException.class.getName()); setField(target.getClass().getDeclaredField("i"), target, 4, false); }
public static void setField( Field field, Object target, Object value, boolean suppressProtection) { doPrivileged((PrivilegedAction<Void>) () -> { field.setAccessible(suppressProtection); return null; }); try { field.set(target, value); } catch (Exception ex) { throw reflectionException(ex); } }
Reflection { public static void setField( Field field, Object target, Object value, boolean suppressProtection) { doPrivileged((PrivilegedAction<Void>) () -> { field.setAccessible(suppressProtection); return null; }); try { field.set(target, value); } catch (Exception ex) { throw reflectionException(ex); } } }
Reflection { public static void setField( Field field, Object target, Object value, boolean suppressProtection) { doPrivileged((PrivilegedAction<Void>) () -> { field.setAccessible(suppressProtection); return null; }); try { field.set(target, value); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); }
Reflection { public static void setField( Field field, Object target, Object value, boolean suppressProtection) { doPrivileged((PrivilegedAction<Void>) () -> { field.setAccessible(suppressProtection); return null; }); try { field.set(target, value); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static void setField( Field field, Object target, Object value, boolean suppressProtection) { doPrivileged((PrivilegedAction<Void>) () -> { field.setAccessible(suppressProtection); return null; }); try { field.set(target, value); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void findingAllDeclaredFieldsOnAClass() throws Exception { List<Field> fields = allDeclaredFieldsOf(Child.class); assertEquals(2, fields.size()); assertThat(fields, hasItem(Child.class.getDeclaredField("s"))); assertThat(fields, hasItem(Parent.class.getDeclaredField("i"))); }
public static List<Field> allDeclaredFieldsOf(Class<?> type) { List<Field> allFields = new ArrayList<>(); for (Class<?> c = type; c != null; c = c.getSuperclass()) Collections.addAll(allFields, c.getDeclaredFields()); List<Field> results = allFields.stream() .filter(f -> !f.isSynthetic()) .collect(toList()); results.forEach(f -> f.setAccessible(true)); return results; }
Reflection { public static List<Field> allDeclaredFieldsOf(Class<?> type) { List<Field> allFields = new ArrayList<>(); for (Class<?> c = type; c != null; c = c.getSuperclass()) Collections.addAll(allFields, c.getDeclaredFields()); List<Field> results = allFields.stream() .filter(f -> !f.isSynthetic()) .collect(toList()); results.forEach(f -> f.setAccessible(true)); return results; } }
Reflection { public static List<Field> allDeclaredFieldsOf(Class<?> type) { List<Field> allFields = new ArrayList<>(); for (Class<?> c = type; c != null; c = c.getSuperclass()) Collections.addAll(allFields, c.getDeclaredFields()); List<Field> results = allFields.stream() .filter(f -> !f.isSynthetic()) .collect(toList()); results.forEach(f -> f.setAccessible(true)); return results; } private Reflection(); }
Reflection { public static List<Field> allDeclaredFieldsOf(Class<?> type) { List<Field> allFields = new ArrayList<>(); for (Class<?> c = type; c != null; c = c.getSuperclass()) Collections.addAll(allFields, c.getDeclaredFields()); List<Field> results = allFields.stream() .filter(f -> !f.isSynthetic()) .collect(toList()); results.forEach(f -> f.setAccessible(true)); return results; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static List<Field> allDeclaredFieldsOf(Class<?> type) { List<Field> allFields = new ArrayList<>(); for (Class<?> c = type; c != null; c = c.getSuperclass()) Collections.addAll(allFields, c.getDeclaredFields()); List<Field> results = allFields.stream() .filter(f -> !f.isSynthetic()) .collect(toList()); results.forEach(f -> f.setAccessible(true)); return results; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void canOnlyGenerateNull() { VoidGenerator generator = new VoidGenerator(); Void value = generator.generate(null, null); assertNull(value); }
@Override public Void generate(SourceOfRandomness random, GenerationStatus status) { return null; }
VoidGenerator extends Generator<Void> { @Override public Void generate(SourceOfRandomness random, GenerationStatus status) { return null; } }
VoidGenerator extends Generator<Void> { @Override public Void generate(SourceOfRandomness random, GenerationStatus status) { return null; } @SuppressWarnings("unchecked") VoidGenerator(); }
VoidGenerator extends Generator<Void> { @Override public Void generate(SourceOfRandomness random, GenerationStatus status) { return null; } @SuppressWarnings("unchecked") VoidGenerator(); @Override Void generate(SourceOfRandomness random, GenerationStatus status); @Override boolean canRegisterAsType(Class<?> type); }
VoidGenerator extends Generator<Void> { @Override public Void generate(SourceOfRandomness random, GenerationStatus status) { return null; } @SuppressWarnings("unchecked") VoidGenerator(); @Override Void generate(SourceOfRandomness random, GenerationStatus status); @Override boolean canRegisterAsType(Class<?> type); }
@Test public void findingField() { Field i = findField(Parent.class, "i"); assertEquals(int.class, i.getType()); }
public static Field findField(Class<?> type, String fieldName) { try { return type.getDeclaredField(fieldName); } catch (NoSuchFieldException ex) { throw reflectionException(ex); } }
Reflection { public static Field findField(Class<?> type, String fieldName) { try { return type.getDeclaredField(fieldName); } catch (NoSuchFieldException ex) { throw reflectionException(ex); } } }
Reflection { public static Field findField(Class<?> type, String fieldName) { try { return type.getDeclaredField(fieldName); } catch (NoSuchFieldException ex) { throw reflectionException(ex); } } private Reflection(); }
Reflection { public static Field findField(Class<?> type, String fieldName) { try { return type.getDeclaredField(fieldName); } catch (NoSuchFieldException ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static Field findField(Class<?> type, String fieldName) { try { return type.getDeclaredField(fieldName); } catch (NoSuchFieldException ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void findingNonExistentField() { thrown.expect(ReflectionException.class); thrown.expectMessage(NoSuchFieldException.class.getName()); findField(Parent.class, "missing"); }
public static Field findField(Class<?> type, String fieldName) { try { return type.getDeclaredField(fieldName); } catch (NoSuchFieldException ex) { throw reflectionException(ex); } }
Reflection { public static Field findField(Class<?> type, String fieldName) { try { return type.getDeclaredField(fieldName); } catch (NoSuchFieldException ex) { throw reflectionException(ex); } } }
Reflection { public static Field findField(Class<?> type, String fieldName) { try { return type.getDeclaredField(fieldName); } catch (NoSuchFieldException ex) { throw reflectionException(ex); } } private Reflection(); }
Reflection { public static Field findField(Class<?> type, String fieldName) { try { return type.getDeclaredField(fieldName); } catch (NoSuchFieldException ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static Field findField(Class<?> type, String fieldName) { try { return type.getDeclaredField(fieldName); } catch (NoSuchFieldException ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void findingAllDeclaredFieldsOnAClassExcludesSynthetics() throws Exception { List<Field> fields = allDeclaredFieldsOf(Outer.Inner.class); assertEquals(1, fields.size()); assertThat(fields, hasItem(Outer.Inner.class.getDeclaredField("s"))); }
public static List<Field> allDeclaredFieldsOf(Class<?> type) { List<Field> allFields = new ArrayList<>(); for (Class<?> c = type; c != null; c = c.getSuperclass()) Collections.addAll(allFields, c.getDeclaredFields()); List<Field> results = allFields.stream() .filter(f -> !f.isSynthetic()) .collect(toList()); results.forEach(f -> f.setAccessible(true)); return results; }
Reflection { public static List<Field> allDeclaredFieldsOf(Class<?> type) { List<Field> allFields = new ArrayList<>(); for (Class<?> c = type; c != null; c = c.getSuperclass()) Collections.addAll(allFields, c.getDeclaredFields()); List<Field> results = allFields.stream() .filter(f -> !f.isSynthetic()) .collect(toList()); results.forEach(f -> f.setAccessible(true)); return results; } }
Reflection { public static List<Field> allDeclaredFieldsOf(Class<?> type) { List<Field> allFields = new ArrayList<>(); for (Class<?> c = type; c != null; c = c.getSuperclass()) Collections.addAll(allFields, c.getDeclaredFields()); List<Field> results = allFields.stream() .filter(f -> !f.isSynthetic()) .collect(toList()); results.forEach(f -> f.setAccessible(true)); return results; } private Reflection(); }
Reflection { public static List<Field> allDeclaredFieldsOf(Class<?> type) { List<Field> allFields = new ArrayList<>(); for (Class<?> c = type; c != null; c = c.getSuperclass()) Collections.addAll(allFields, c.getDeclaredFields()); List<Field> results = allFields.stream() .filter(f -> !f.isSynthetic()) .collect(toList()); results.forEach(f -> f.setAccessible(true)); return results; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static List<Field> allDeclaredFieldsOf(Class<?> type) { List<Field> allFields = new ArrayList<>(); for (Class<?> c = type; c != null; c = c.getSuperclass()) Collections.addAll(allFields, c.getDeclaredFields()); List<Field> results = allFields.stream() .filter(f -> !f.isSynthetic()) .collect(toList()); results.forEach(f -> f.setAccessible(true)); return results; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void checkFindNextPowerOfTwoLong() { assertEquals(1, findNextPowerOfTwoLong(1)); assertEquals(2, findNextPowerOfTwoLong(2)); assertEquals(4, findNextPowerOfTwoLong(3)); assertEquals(4, findNextPowerOfTwoLong(4)); assertEquals(8, findNextPowerOfTwoLong(5)); assertEquals((long) 1 << 61, findNextPowerOfTwoLong((long) 1 << 61)); assertEquals((long) 1 << 62, findNextPowerOfTwoLong(1 + (long) 1 << 61)); }
static long findNextPowerOfTwoLong(long positiveLong) { return isPowerOfTwoLong(positiveLong) ? positiveLong : ((long) 1) << (64 - Long.numberOfLeadingZeros(positiveLong)); }
Ranges { static long findNextPowerOfTwoLong(long positiveLong) { return isPowerOfTwoLong(positiveLong) ? positiveLong : ((long) 1) << (64 - Long.numberOfLeadingZeros(positiveLong)); } }
Ranges { static long findNextPowerOfTwoLong(long positiveLong) { return isPowerOfTwoLong(positiveLong) ? positiveLong : ((long) 1) << (64 - Long.numberOfLeadingZeros(positiveLong)); } private Ranges(); }
Ranges { static long findNextPowerOfTwoLong(long positiveLong) { return isPowerOfTwoLong(positiveLong) ? positiveLong : ((long) 1) << (64 - Long.numberOfLeadingZeros(positiveLong)); } private Ranges(); static int checkRange( Type type, T min, T max); static BigInteger choose( SourceOfRandomness random, BigInteger min, BigInteger max); static long choose(SourceOfRandomness random, long min, long max); }
Ranges { static long findNextPowerOfTwoLong(long positiveLong) { return isPowerOfTwoLong(positiveLong) ? positiveLong : ((long) 1) << (64 - Long.numberOfLeadingZeros(positiveLong)); } private Ranges(); static int checkRange( Type type, T min, T max); static BigInteger choose( SourceOfRandomness random, BigInteger min, BigInteger max); static long choose(SourceOfRandomness random, long min, long max); }
@Test public void weakSanityCheckForDistributionOfChooseLongs() { boolean[] hits = new boolean[5]; SourceOfRandomness random = new SourceOfRandomness(new Random(0)); for (int i = 0; i < 100; i++) { hits[(int) Ranges.choose(random, 0, (long) hits.length - 1)] = true; } for (boolean hit : hits) { assertTrue(hit); } }
public static BigInteger choose( SourceOfRandomness random, BigInteger min, BigInteger max) { BigInteger range = max.subtract(min).add(BigInteger.ONE); BigInteger generated; do { generated = random.nextBigInteger(range.bitLength()); } while (generated.compareTo(range) >= 0); return generated.add(min); }
Ranges { public static BigInteger choose( SourceOfRandomness random, BigInteger min, BigInteger max) { BigInteger range = max.subtract(min).add(BigInteger.ONE); BigInteger generated; do { generated = random.nextBigInteger(range.bitLength()); } while (generated.compareTo(range) >= 0); return generated.add(min); } }
Ranges { public static BigInteger choose( SourceOfRandomness random, BigInteger min, BigInteger max) { BigInteger range = max.subtract(min).add(BigInteger.ONE); BigInteger generated; do { generated = random.nextBigInteger(range.bitLength()); } while (generated.compareTo(range) >= 0); return generated.add(min); } private Ranges(); }
Ranges { public static BigInteger choose( SourceOfRandomness random, BigInteger min, BigInteger max) { BigInteger range = max.subtract(min).add(BigInteger.ONE); BigInteger generated; do { generated = random.nextBigInteger(range.bitLength()); } while (generated.compareTo(range) >= 0); return generated.add(min); } private Ranges(); static int checkRange( Type type, T min, T max); static BigInteger choose( SourceOfRandomness random, BigInteger min, BigInteger max); static long choose(SourceOfRandomness random, long min, long max); }
Ranges { public static BigInteger choose( SourceOfRandomness random, BigInteger min, BigInteger max) { BigInteger range = max.subtract(min).add(BigInteger.ONE); BigInteger generated; do { generated = random.nextBigInteger(range.bitLength()); } while (generated.compareTo(range) >= 0); return generated.add(min); } private Ranges(); static int checkRange( Type type, T min, T max); static BigInteger choose( SourceOfRandomness random, BigInteger min, BigInteger max); static long choose(SourceOfRandomness random, long min, long max); }
@Test public void choosingFromSet() { Set<String> names = new LinkedHashSet<>(asList("alpha", "bravo", "charlie", "delta")); when(random.nextInt(names.size())).thenReturn(2); assertEquals("charlie", Items.choose(names, random)); }
@SuppressWarnings("unchecked") public static <T> T choose(Collection<T> items, SourceOfRandomness random) { int size = items.size(); if (size == 0) { throw new IllegalArgumentException( "Collection is empty, can't pick an element from it"); } if (items instanceof RandomAccess && items instanceof List<?>) { List<T> list = (List<T>) items; return size == 1 ? list.get(0) : list.get(random.nextInt(size)); } if (size == 1) { return items.iterator().next(); } Object[] array = items.toArray(new Object[0]); return (T) array[random.nextInt(array.length)]; }
Items { @SuppressWarnings("unchecked") public static <T> T choose(Collection<T> items, SourceOfRandomness random) { int size = items.size(); if (size == 0) { throw new IllegalArgumentException( "Collection is empty, can't pick an element from it"); } if (items instanceof RandomAccess && items instanceof List<?>) { List<T> list = (List<T>) items; return size == 1 ? list.get(0) : list.get(random.nextInt(size)); } if (size == 1) { return items.iterator().next(); } Object[] array = items.toArray(new Object[0]); return (T) array[random.nextInt(array.length)]; } }
Items { @SuppressWarnings("unchecked") public static <T> T choose(Collection<T> items, SourceOfRandomness random) { int size = items.size(); if (size == 0) { throw new IllegalArgumentException( "Collection is empty, can't pick an element from it"); } if (items instanceof RandomAccess && items instanceof List<?>) { List<T> list = (List<T>) items; return size == 1 ? list.get(0) : list.get(random.nextInt(size)); } if (size == 1) { return items.iterator().next(); } Object[] array = items.toArray(new Object[0]); return (T) array[random.nextInt(array.length)]; } private Items(); }
Items { @SuppressWarnings("unchecked") public static <T> T choose(Collection<T> items, SourceOfRandomness random) { int size = items.size(); if (size == 0) { throw new IllegalArgumentException( "Collection is empty, can't pick an element from it"); } if (items instanceof RandomAccess && items instanceof List<?>) { List<T> list = (List<T>) items; return size == 1 ? list.get(0) : list.get(random.nextInt(size)); } if (size == 1) { return items.iterator().next(); } Object[] array = items.toArray(new Object[0]); return (T) array[random.nextInt(array.length)]; } private Items(); @SuppressWarnings("unchecked") static T choose(Collection<T> items, SourceOfRandomness random); static T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random); }
Items { @SuppressWarnings("unchecked") public static <T> T choose(Collection<T> items, SourceOfRandomness random) { int size = items.size(); if (size == 0) { throw new IllegalArgumentException( "Collection is empty, can't pick an element from it"); } if (items instanceof RandomAccess && items instanceof List<?>) { List<T> list = (List<T>) items; return size == 1 ? list.get(0) : list.get(random.nextInt(size)); } if (size == 1) { return items.iterator().next(); } Object[] array = items.toArray(new Object[0]); return (T) array[random.nextInt(array.length)]; } private Items(); @SuppressWarnings("unchecked") static T choose(Collection<T> items, SourceOfRandomness random); static T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random); }
@Test public void singleWeightedItem() { when(random.nextInt(2)).thenReturn(1); assertEquals("a", Items.chooseWeighted(singletonList(first), random)); }
public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); }
Items { public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); } }
Items { public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); } private Items(); }
Items { public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); } private Items(); @SuppressWarnings("unchecked") static T choose(Collection<T> items, SourceOfRandomness random); static T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random); }
Items { public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); } private Items(); @SuppressWarnings("unchecked") static T choose(Collection<T> items, SourceOfRandomness random); static T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random); }
@Test public void choosingFirstOfManyWeightedItems() { when(random.nextInt(9)).thenReturn(0).thenReturn(1); assertEquals("a", Items.chooseWeighted(asList(first, second, third), random)); assertEquals("a", Items.chooseWeighted(asList(first, second, third), random)); }
public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); }
Items { public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); } }
Items { public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); } private Items(); }
Items { public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); } private Items(); @SuppressWarnings("unchecked") static T choose(Collection<T> items, SourceOfRandomness random); static T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random); }
Items { public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); } private Items(); @SuppressWarnings("unchecked") static T choose(Collection<T> items, SourceOfRandomness random); static T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random); }
@Test public void choosingMiddleOfManyWeightedItems() { when(random.nextInt(9)).thenReturn(2).thenReturn(3).thenReturn(4); assertEquals("b", Items.chooseWeighted(asList(first, second, third), random)); assertEquals("b", Items.chooseWeighted(asList(first, second, third), random)); assertEquals("b", Items.chooseWeighted(asList(first, second, third), random)); }
public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); }
Items { public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); } }
Items { public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); } private Items(); }
Items { public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); } private Items(); @SuppressWarnings("unchecked") static T choose(Collection<T> items, SourceOfRandomness random); static T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random); }
Items { public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); } private Items(); @SuppressWarnings("unchecked") static T choose(Collection<T> items, SourceOfRandomness random); static T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random); }
@Test public void choosingLastOfManyWeightedItems() { when(random.nextInt(9)).thenReturn(5).thenReturn(6).thenReturn(7).thenReturn(8); assertEquals("c", Items.chooseWeighted(asList(first, second, third), random)); assertEquals("c", Items.chooseWeighted(asList(first, second, third), random)); assertEquals("c", Items.chooseWeighted(asList(first, second, third), random)); assertEquals("c", Items.chooseWeighted(asList(first, second, third), random)); }
public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); }
Items { public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); } }
Items { public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); } private Items(); }
Items { public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); } private Items(); @SuppressWarnings("unchecked") static T choose(Collection<T> items, SourceOfRandomness random); static T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random); }
Items { public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); } private Items(); @SuppressWarnings("unchecked") static T choose(Collection<T> items, SourceOfRandomness random); static T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random); }
@Test public void equalsBasedOnIdentity() { Predicate<?> duplicate = makeLambda(Predicate.class, returnValueGenerator, status); assertEquals(predicate, predicate); assertEquals(duplicate, duplicate); assertNotEquals(predicate, duplicate); assertNotEquals(duplicate, predicate); }
public static <T, U> T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status) { if (singleAbstractMethodOf(lambdaType) == null) { throw new IllegalArgumentException( lambdaType + " is not a functional interface type"); } return lambdaType.cast( newProxyInstance( lambdaType.getClassLoader(), new Class<?>[] { lambdaType }, new LambdaInvocationHandler<>( lambdaType, returnValueGenerator, status.attempts()))); }
Lambdas { public static <T, U> T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status) { if (singleAbstractMethodOf(lambdaType) == null) { throw new IllegalArgumentException( lambdaType + " is not a functional interface type"); } return lambdaType.cast( newProxyInstance( lambdaType.getClassLoader(), new Class<?>[] { lambdaType }, new LambdaInvocationHandler<>( lambdaType, returnValueGenerator, status.attempts()))); } }
Lambdas { public static <T, U> T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status) { if (singleAbstractMethodOf(lambdaType) == null) { throw new IllegalArgumentException( lambdaType + " is not a functional interface type"); } return lambdaType.cast( newProxyInstance( lambdaType.getClassLoader(), new Class<?>[] { lambdaType }, new LambdaInvocationHandler<>( lambdaType, returnValueGenerator, status.attempts()))); } private Lambdas(); }
Lambdas { public static <T, U> T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status) { if (singleAbstractMethodOf(lambdaType) == null) { throw new IllegalArgumentException( lambdaType + " is not a functional interface type"); } return lambdaType.cast( newProxyInstance( lambdaType.getClassLoader(), new Class<?>[] { lambdaType }, new LambdaInvocationHandler<>( lambdaType, returnValueGenerator, status.attempts()))); } private Lambdas(); static T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status); }
Lambdas { public static <T, U> T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status) { if (singleAbstractMethodOf(lambdaType) == null) { throw new IllegalArgumentException( lambdaType + " is not a functional interface type"); } return lambdaType.cast( newProxyInstance( lambdaType.getClassLoader(), new Class<?>[] { lambdaType }, new LambdaInvocationHandler<>( lambdaType, returnValueGenerator, status.attempts()))); } private Lambdas(); static T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status); }
@Test public void getRequestMappings_noClassAnnotation() throws NoSuchMethodException { Class<?> ctrl = StandardController.class; Method none = ctrl.getDeclaredMethod("none"); Method slash = ctrl.getDeclaredMethod("slash"); Method slashPath = ctrl.getDeclaredMethod("slashPath"); Method longPath = ctrl.getDeclaredMethod("slashLongPath"); Method pathAttribute = ctrl.getDeclaredMethod("pathAttribute"); assertEquals(singletonList("/"), MappingsResolver.getRequestMappings(none, ctrl)); assertEquals(singletonList("/"), MappingsResolver.getRequestMappings(slash, ctrl)); assertEquals(singletonList("/path"), MappingsResolver.getRequestMappings(slashPath, ctrl)); assertEquals(singletonList("/long/path"), MappingsResolver.getRequestMappings(longPath, ctrl)); assertEquals(singletonList("/path/attr"), MappingsResolver.getRequestMappings(pathAttribute, ctrl)); }
public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); }
MappingsResolver { public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); } }
MappingsResolver { public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); } }
MappingsResolver { public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); } static List<String> getRequestMappings(Method method, Class<?> controller); static List<String> getMessageMappings(Method method, Class<?> controller); static List<String> getSubscribeMappings(Method method, Class<?> controller); }
MappingsResolver { public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); } static List<String> getRequestMappings(Method method, Class<?> controller); static List<String> getMessageMappings(Method method, Class<?> controller); static List<String> getSubscribeMappings(Method method, Class<?> controller); }
@Test public void getFieldTypes_primitive() { List<Property> props = scanner.getProperties(int.class); assertTrue(props.isEmpty()); }
@Override public List<Property> getProperties(Type type) { Class<?> clazz = extractClass(type); return getAllFields(clazz).stream() .filter(FieldPropertyScanner::isRelevantWhenSerialized) .map(FieldPropertyScanner::toProperty) .collect(toList()); }
FieldPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { Class<?> clazz = extractClass(type); return getAllFields(clazz).stream() .filter(FieldPropertyScanner::isRelevantWhenSerialized) .map(FieldPropertyScanner::toProperty) .collect(toList()); } }
FieldPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { Class<?> clazz = extractClass(type); return getAllFields(clazz).stream() .filter(FieldPropertyScanner::isRelevantWhenSerialized) .map(FieldPropertyScanner::toProperty) .collect(toList()); } }
FieldPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { Class<?> clazz = extractClass(type); return getAllFields(clazz).stream() .filter(FieldPropertyScanner::isRelevantWhenSerialized) .map(FieldPropertyScanner::toProperty) .collect(toList()); } @Override List<Property> getProperties(Type type); }
FieldPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { Class<?> clazz = extractClass(type); return getAllFields(clazz).stream() .filter(FieldPropertyScanner::isRelevantWhenSerialized) .map(FieldPropertyScanner::toProperty) .collect(toList()); } @Override List<Property> getProperties(Type type); }
@Test public void getFieldTypes_excludesTransient() throws NoSuchFieldException { Set<Property> props = new HashSet<>(); props.add(createFieldProperty("stringField", String.class, CustomObject.class)); props.add(createFieldProperty("intField", int.class, CustomObject.class)); props.add(createFieldProperty("objField", Object.class, CustomObject.class)); props.add(new Property("genericField", List.class, new TypeToken<List<Integer>>() {}.getType(), CustomObject.class.getDeclaredField("genericField"))); assertEquals(props, new HashSet<>(scanner.getProperties(CustomObject.class))); }
@Override public List<Property> getProperties(Type type) { Class<?> clazz = extractClass(type); return getAllFields(clazz).stream() .filter(FieldPropertyScanner::isRelevantWhenSerialized) .map(FieldPropertyScanner::toProperty) .collect(toList()); }
FieldPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { Class<?> clazz = extractClass(type); return getAllFields(clazz).stream() .filter(FieldPropertyScanner::isRelevantWhenSerialized) .map(FieldPropertyScanner::toProperty) .collect(toList()); } }
FieldPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { Class<?> clazz = extractClass(type); return getAllFields(clazz).stream() .filter(FieldPropertyScanner::isRelevantWhenSerialized) .map(FieldPropertyScanner::toProperty) .collect(toList()); } }
FieldPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { Class<?> clazz = extractClass(type); return getAllFields(clazz).stream() .filter(FieldPropertyScanner::isRelevantWhenSerialized) .map(FieldPropertyScanner::toProperty) .collect(toList()); } @Override List<Property> getProperties(Type type); }
FieldPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { Class<?> clazz = extractClass(type); return getAllFields(clazz).stream() .filter(FieldPropertyScanner::isRelevantWhenSerialized) .map(FieldPropertyScanner::toProperty) .collect(toList()); } @Override List<Property> getProperties(Type type); }
@Test public void getFieldTypes_inheritedFields() throws NoSuchFieldException { Set<Property> props = new HashSet<>(); props.add(createFieldProperty("parentField", Float.class, Parent.class)); props.add(createFieldProperty("childField", Double.class, Child.class)); assertEquals(props, new HashSet<>(scanner.getProperties(Child.class))); }
@Override public List<Property> getProperties(Type type) { Class<?> clazz = extractClass(type); return getAllFields(clazz).stream() .filter(FieldPropertyScanner::isRelevantWhenSerialized) .map(FieldPropertyScanner::toProperty) .collect(toList()); }
FieldPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { Class<?> clazz = extractClass(type); return getAllFields(clazz).stream() .filter(FieldPropertyScanner::isRelevantWhenSerialized) .map(FieldPropertyScanner::toProperty) .collect(toList()); } }
FieldPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { Class<?> clazz = extractClass(type); return getAllFields(clazz).stream() .filter(FieldPropertyScanner::isRelevantWhenSerialized) .map(FieldPropertyScanner::toProperty) .collect(toList()); } }
FieldPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { Class<?> clazz = extractClass(type); return getAllFields(clazz).stream() .filter(FieldPropertyScanner::isRelevantWhenSerialized) .map(FieldPropertyScanner::toProperty) .collect(toList()); } @Override List<Property> getProperties(Type type); }
FieldPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { Class<?> clazz = extractClass(type); return getAllFields(clazz).stream() .filter(FieldPropertyScanner::isRelevantWhenSerialized) .map(FieldPropertyScanner::toProperty) .collect(toList()); } @Override List<Property> getProperties(Type type); }
@Test public void getFieldTypes_enum() throws NoSuchFieldException { Set<Property> props = new HashSet<>(); props.add(createFieldProperty("name", String.class, Enum.class)); props.add(createFieldProperty("ordinal", int.class, Enum.class)); props.add(createFieldProperty("intField", int.class, MyEnum.class)); props.add(createFieldProperty("doubleField", Double.class, MyEnum.class)); assertEquals(props, new HashSet<>(scanner.getProperties(MyEnum.class))); }
@Override public List<Property> getProperties(Type type) { Class<?> clazz = extractClass(type); return getAllFields(clazz).stream() .filter(FieldPropertyScanner::isRelevantWhenSerialized) .map(FieldPropertyScanner::toProperty) .collect(toList()); }
FieldPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { Class<?> clazz = extractClass(type); return getAllFields(clazz).stream() .filter(FieldPropertyScanner::isRelevantWhenSerialized) .map(FieldPropertyScanner::toProperty) .collect(toList()); } }
FieldPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { Class<?> clazz = extractClass(type); return getAllFields(clazz).stream() .filter(FieldPropertyScanner::isRelevantWhenSerialized) .map(FieldPropertyScanner::toProperty) .collect(toList()); } }
FieldPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { Class<?> clazz = extractClass(type); return getAllFields(clazz).stream() .filter(FieldPropertyScanner::isRelevantWhenSerialized) .map(FieldPropertyScanner::toProperty) .collect(toList()); } @Override List<Property> getProperties(Type type); }
FieldPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { Class<?> clazz = extractClass(type); return getAllFields(clazz).stream() .filter(FieldPropertyScanner::isRelevantWhenSerialized) .map(FieldPropertyScanner::toProperty) .collect(toList()); } @Override List<Property> getProperties(Type type); }
@Test public void findTypes_simpleString() { Set<Type> rootTypes = Collections.singleton(String.class); assertSetEquals(explorer.findTypesToDocument(rootTypes), String.class); }
@Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; }
RecursivePropertyTypeScanner implements TypeScanner { @Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; } }
RecursivePropertyTypeScanner implements TypeScanner { @Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; } RecursivePropertyTypeScanner(PropertyScanner scanner); }
RecursivePropertyTypeScanner implements TypeScanner { @Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; } RecursivePropertyTypeScanner(PropertyScanner scanner); Predicate<? super Class<?>> getTypeFilter(); void setTypeFilter(Predicate<? super Class<?>> typeFilter); Predicate<? super Class<?>> getTypeInspectionFilter(); void setTypeInspectionFilter(Predicate<? super Class<?>> typeInspectionFilter); Function<Class<?>, Set<Class<?>>> getTypeMapper(); void setTypeMapper(Function<Class<?>, Set<Class<?>>> mapper); @Override Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes); }
RecursivePropertyTypeScanner implements TypeScanner { @Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; } RecursivePropertyTypeScanner(PropertyScanner scanner); Predicate<? super Class<?>> getTypeFilter(); void setTypeFilter(Predicate<? super Class<?>> typeFilter); Predicate<? super Class<?>> getTypeInspectionFilter(); void setTypeInspectionFilter(Predicate<? super Class<?>> typeInspectionFilter); Function<Class<?>, Set<Class<?>>> getTypeMapper(); void setTypeMapper(Function<Class<?>, Set<Class<?>>> mapper); @Override Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes); }
@Test public void findTypes_simpleCharacter() { Set<Type> rootTypes = Collections.singleton(Character.class); assertSetEquals(explorer.findTypesToDocument(rootTypes), Character.class); }
@Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; }
RecursivePropertyTypeScanner implements TypeScanner { @Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; } }
RecursivePropertyTypeScanner implements TypeScanner { @Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; } RecursivePropertyTypeScanner(PropertyScanner scanner); }
RecursivePropertyTypeScanner implements TypeScanner { @Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; } RecursivePropertyTypeScanner(PropertyScanner scanner); Predicate<? super Class<?>> getTypeFilter(); void setTypeFilter(Predicate<? super Class<?>> typeFilter); Predicate<? super Class<?>> getTypeInspectionFilter(); void setTypeInspectionFilter(Predicate<? super Class<?>> typeInspectionFilter); Function<Class<?>, Set<Class<?>>> getTypeMapper(); void setTypeMapper(Function<Class<?>, Set<Class<?>>> mapper); @Override Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes); }
RecursivePropertyTypeScanner implements TypeScanner { @Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; } RecursivePropertyTypeScanner(PropertyScanner scanner); Predicate<? super Class<?>> getTypeFilter(); void setTypeFilter(Predicate<? super Class<?>> typeFilter); Predicate<? super Class<?>> getTypeInspectionFilter(); void setTypeInspectionFilter(Predicate<? super Class<?>> typeInspectionFilter); Function<Class<?>, Set<Class<?>>> getTypeMapper(); void setTypeMapper(Function<Class<?>, Set<Class<?>>> mapper); @Override Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes); }
@Test public void findTypes_customType() { Set<Type> rootTypes = Collections.singleton(Custom.class); assertSetEquals(explorer.findTypesToDocument(rootTypes), Custom.class, Long.class); }
@Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; }
RecursivePropertyTypeScanner implements TypeScanner { @Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; } }
RecursivePropertyTypeScanner implements TypeScanner { @Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; } RecursivePropertyTypeScanner(PropertyScanner scanner); }
RecursivePropertyTypeScanner implements TypeScanner { @Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; } RecursivePropertyTypeScanner(PropertyScanner scanner); Predicate<? super Class<?>> getTypeFilter(); void setTypeFilter(Predicate<? super Class<?>> typeFilter); Predicate<? super Class<?>> getTypeInspectionFilter(); void setTypeInspectionFilter(Predicate<? super Class<?>> typeInspectionFilter); Function<Class<?>, Set<Class<?>>> getTypeMapper(); void setTypeMapper(Function<Class<?>, Set<Class<?>>> mapper); @Override Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes); }
RecursivePropertyTypeScanner implements TypeScanner { @Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; } RecursivePropertyTypeScanner(PropertyScanner scanner); Predicate<? super Class<?>> getTypeFilter(); void setTypeFilter(Predicate<? super Class<?>> typeFilter); Predicate<? super Class<?>> getTypeInspectionFilter(); void setTypeInspectionFilter(Predicate<? super Class<?>> typeInspectionFilter); Function<Class<?>, Set<Class<?>>> getTypeMapper(); void setTypeMapper(Function<Class<?>, Set<Class<?>>> mapper); @Override Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes); }
@Test public void findTypes_inheritedFields() { Set<Type> rootTypes = Collections.singleton(Child.class); assertSetEquals(explorer.findTypesToDocument(rootTypes), Child.class, Double.class, Long.class); }
@Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; }
RecursivePropertyTypeScanner implements TypeScanner { @Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; } }
RecursivePropertyTypeScanner implements TypeScanner { @Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; } RecursivePropertyTypeScanner(PropertyScanner scanner); }
RecursivePropertyTypeScanner implements TypeScanner { @Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; } RecursivePropertyTypeScanner(PropertyScanner scanner); Predicate<? super Class<?>> getTypeFilter(); void setTypeFilter(Predicate<? super Class<?>> typeFilter); Predicate<? super Class<?>> getTypeInspectionFilter(); void setTypeInspectionFilter(Predicate<? super Class<?>> typeInspectionFilter); Function<Class<?>, Set<Class<?>>> getTypeMapper(); void setTypeMapper(Function<Class<?>, Set<Class<?>>> mapper); @Override Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes); }
RecursivePropertyTypeScanner implements TypeScanner { @Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; } RecursivePropertyTypeScanner(PropertyScanner scanner); Predicate<? super Class<?>> getTypeFilter(); void setTypeFilter(Predicate<? super Class<?>> typeFilter); Predicate<? super Class<?>> getTypeInspectionFilter(); void setTypeInspectionFilter(Predicate<? super Class<?>> typeInspectionFilter); Function<Class<?>, Set<Class<?>>> getTypeMapper(); void setTypeMapper(Function<Class<?>, Set<Class<?>>> mapper); @Override Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes); }
@Test public void findTypes_complexHierarchy() { Set<Type> rootTypes = Collections.singleton(TestRoot.class); assertSetEquals(explorer.findTypesToDocument(rootTypes), TestRoot.class, WithCustomObject.class, WithPrimitives.class, Custom.class, Long.class, String.class, int.class); }
@Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; }
RecursivePropertyTypeScanner implements TypeScanner { @Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; } }
RecursivePropertyTypeScanner implements TypeScanner { @Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; } RecursivePropertyTypeScanner(PropertyScanner scanner); }
RecursivePropertyTypeScanner implements TypeScanner { @Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; } RecursivePropertyTypeScanner(PropertyScanner scanner); Predicate<? super Class<?>> getTypeFilter(); void setTypeFilter(Predicate<? super Class<?>> typeFilter); Predicate<? super Class<?>> getTypeInspectionFilter(); void setTypeInspectionFilter(Predicate<? super Class<?>> typeInspectionFilter); Function<Class<?>, Set<Class<?>>> getTypeMapper(); void setTypeMapper(Function<Class<?>, Set<Class<?>>> mapper); @Override Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes); }
RecursivePropertyTypeScanner implements TypeScanner { @Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; } RecursivePropertyTypeScanner(PropertyScanner scanner); Predicate<? super Class<?>> getTypeFilter(); void setTypeFilter(Predicate<? super Class<?>> typeFilter); Predicate<? super Class<?>> getTypeInspectionFilter(); void setTypeInspectionFilter(Predicate<? super Class<?>> typeInspectionFilter); Function<Class<?>, Set<Class<?>>> getTypeMapper(); void setTypeMapper(Function<Class<?>, Set<Class<?>>> mapper); @Override Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes); }
@Test public void apply_concreteClass() { assertEquals(mapper.apply(SimpleAImpl.class), SimpleAImpl.class); assertEquals(mapper.apply(ConcreteAImpl.class), ConcreteAImpl.class); assertEquals(mapper.apply(BImpl.class), BImpl.class); }
@Override public Set<Class<?>> apply(Class<?> type) { if (isAbstract(type)) { return getImplementationsOf(type); } return Collections.singleton(type); }
ConcreteSubtypesMapper implements Function<Class<?>, Set<Class<?>>> { @Override public Set<Class<?>> apply(Class<?> type) { if (isAbstract(type)) { return getImplementationsOf(type); } return Collections.singleton(type); } }
ConcreteSubtypesMapper implements Function<Class<?>, Set<Class<?>>> { @Override public Set<Class<?>> apply(Class<?> type) { if (isAbstract(type)) { return getImplementationsOf(type); } return Collections.singleton(type); } ConcreteSubtypesMapper(Reflections reflections); }
ConcreteSubtypesMapper implements Function<Class<?>, Set<Class<?>>> { @Override public Set<Class<?>> apply(Class<?> type) { if (isAbstract(type)) { return getImplementationsOf(type); } return Collections.singleton(type); } ConcreteSubtypesMapper(Reflections reflections); @Override Set<Class<?>> apply(Class<?> type); }
ConcreteSubtypesMapper implements Function<Class<?>, Set<Class<?>>> { @Override public Set<Class<?>> apply(Class<?> type) { if (isAbstract(type)) { return getImplementationsOf(type); } return Collections.singleton(type); } ConcreteSubtypesMapper(Reflections reflections); @Override Set<Class<?>> apply(Class<?> type); }
@Test public void getRequestMappings_emptyClassAnnotation() throws NoSuchMethodException { Class<?> ctrl = EmptyAnnotatedController.class; Method none = ctrl.getDeclaredMethod("none"); Method test = ctrl.getDeclaredMethod("test"); assertEquals(singletonList("/"), MappingsResolver.getRequestMappings(none, ctrl)); assertEquals(singletonList("/test"), MappingsResolver.getRequestMappings(test, ctrl)); }
public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); }
MappingsResolver { public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); } }
MappingsResolver { public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); } }
MappingsResolver { public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); } static List<String> getRequestMappings(Method method, Class<?> controller); static List<String> getMessageMappings(Method method, Class<?> controller); static List<String> getSubscribeMappings(Method method, Class<?> controller); }
MappingsResolver { public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); } static List<String> getRequestMappings(Method method, Class<?> controller); static List<String> getMessageMappings(Method method, Class<?> controller); static List<String> getSubscribeMappings(Method method, Class<?> controller); }
@Test public void apply_abstractClass() { assertEquals(mapper.apply(AbstractA.class), ConcreteAImpl.class); }
@Override public Set<Class<?>> apply(Class<?> type) { if (isAbstract(type)) { return getImplementationsOf(type); } return Collections.singleton(type); }
ConcreteSubtypesMapper implements Function<Class<?>, Set<Class<?>>> { @Override public Set<Class<?>> apply(Class<?> type) { if (isAbstract(type)) { return getImplementationsOf(type); } return Collections.singleton(type); } }
ConcreteSubtypesMapper implements Function<Class<?>, Set<Class<?>>> { @Override public Set<Class<?>> apply(Class<?> type) { if (isAbstract(type)) { return getImplementationsOf(type); } return Collections.singleton(type); } ConcreteSubtypesMapper(Reflections reflections); }
ConcreteSubtypesMapper implements Function<Class<?>, Set<Class<?>>> { @Override public Set<Class<?>> apply(Class<?> type) { if (isAbstract(type)) { return getImplementationsOf(type); } return Collections.singleton(type); } ConcreteSubtypesMapper(Reflections reflections); @Override Set<Class<?>> apply(Class<?> type); }
ConcreteSubtypesMapper implements Function<Class<?>, Set<Class<?>>> { @Override public Set<Class<?>> apply(Class<?> type) { if (isAbstract(type)) { return getImplementationsOf(type); } return Collections.singleton(type); } ConcreteSubtypesMapper(Reflections reflections); @Override Set<Class<?>> apply(Class<?> type); }
@Test public void apply_interface() { assertEquals(mapper.apply(B.class), BImpl.class); assertEquals(mapper.apply(A.class), SimpleAImpl.class, ConcreteAImpl.class, BImpl.class); }
@Override public Set<Class<?>> apply(Class<?> type) { if (isAbstract(type)) { return getImplementationsOf(type); } return Collections.singleton(type); }
ConcreteSubtypesMapper implements Function<Class<?>, Set<Class<?>>> { @Override public Set<Class<?>> apply(Class<?> type) { if (isAbstract(type)) { return getImplementationsOf(type); } return Collections.singleton(type); } }
ConcreteSubtypesMapper implements Function<Class<?>, Set<Class<?>>> { @Override public Set<Class<?>> apply(Class<?> type) { if (isAbstract(type)) { return getImplementationsOf(type); } return Collections.singleton(type); } ConcreteSubtypesMapper(Reflections reflections); }
ConcreteSubtypesMapper implements Function<Class<?>, Set<Class<?>>> { @Override public Set<Class<?>> apply(Class<?> type) { if (isAbstract(type)) { return getImplementationsOf(type); } return Collections.singleton(type); } ConcreteSubtypesMapper(Reflections reflections); @Override Set<Class<?>> apply(Class<?> type); }
ConcreteSubtypesMapper implements Function<Class<?>, Set<Class<?>>> { @Override public Set<Class<?>> apply(Class<?> type) { if (isAbstract(type)) { return getImplementationsOf(type); } return Collections.singleton(type); } ConcreteSubtypesMapper(Reflections reflections); @Override Set<Class<?>> apply(Class<?> type); }
@Test public void getRequestMappings_classAnnotationWithPrefix() throws NoSuchMethodException { Class<?> ctrl = PrefixAnnotatedController.class; Method none = ctrl.getDeclaredMethod("none"); Method test = ctrl.getDeclaredMethod("test"); assertEquals(singletonList("/prefix"), MappingsResolver.getRequestMappings(none, ctrl)); assertEquals(singletonList("/prefix/test"), MappingsResolver.getRequestMappings(test, ctrl)); }
public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); }
MappingsResolver { public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); } }
MappingsResolver { public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); } }
MappingsResolver { public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); } static List<String> getRequestMappings(Method method, Class<?> controller); static List<String> getMessageMappings(Method method, Class<?> controller); static List<String> getSubscribeMappings(Method method, Class<?> controller); }
MappingsResolver { public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); } static List<String> getRequestMappings(Method method, Class<?> controller); static List<String> getMessageMappings(Method method, Class<?> controller); static List<String> getSubscribeMappings(Method method, Class<?> controller); }
@Test public void getRequestMappings_childController_prefixOverride() throws NoSuchMethodException { Class<?> ctrl = PrefixOverrideChildController.class; Method none = ctrl.getMethod("none"); Method test = ctrl.getMethod("test"); assertEquals(singletonList("/child"), MappingsResolver.getRequestMappings(none, ctrl)); assertEquals(singletonList("/child/test"), MappingsResolver.getRequestMappings(test, ctrl)); }
public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); }
MappingsResolver { public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); } }
MappingsResolver { public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); } }
MappingsResolver { public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); } static List<String> getRequestMappings(Method method, Class<?> controller); static List<String> getMessageMappings(Method method, Class<?> controller); static List<String> getSubscribeMappings(Method method, Class<?> controller); }
MappingsResolver { public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); } static List<String> getRequestMappings(Method method, Class<?> controller); static List<String> getMessageMappings(Method method, Class<?> controller); static List<String> getSubscribeMappings(Method method, Class<?> controller); }
@Test public void getRequestMappings_multiplePaths() throws NoSuchMethodException { Class<?> ctrl = MultiPathController.class; Method test = ctrl.getMethod("test"); List<String> expectedPaths = Arrays.asList("/path1/path3", "/path1/path4", "/path2/path3", "/path2/path4"); assertEquals(expectedPaths, MappingsResolver.getRequestMappings(test, ctrl)); }
public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); }
MappingsResolver { public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); } }
MappingsResolver { public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); } }
MappingsResolver { public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); } static List<String> getRequestMappings(Method method, Class<?> controller); static List<String> getMessageMappings(Method method, Class<?> controller); static List<String> getSubscribeMappings(Method method, Class<?> controller); }
MappingsResolver { public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); } static List<String> getRequestMappings(Method method, Class<?> controller); static List<String> getMessageMappings(Method method, Class<?> controller); static List<String> getSubscribeMappings(Method method, Class<?> controller); }
@Test public void defaultValueFor_primitives() { assertEquals(0, Defaults.defaultValueFor(byte.class)); assertEquals(0, Defaults.defaultValueFor(short.class)); assertEquals(0, Defaults.defaultValueFor(int.class)); assertEquals(0L, Defaults.defaultValueFor(long.class)); assertEquals(0f, Defaults.defaultValueFor(float.class)); assertEquals(0.0, Defaults.defaultValueFor(double.class)); assertEquals(false, Defaults.defaultValueFor(boolean.class)); assertEquals('\0', Defaults.defaultValueFor(char.class)); }
public static Object defaultValueFor(@Nullable Class<?> type) { if (type == null) { return null; } return primitiveDefaults.get(type); }
Defaults { public static Object defaultValueFor(@Nullable Class<?> type) { if (type == null) { return null; } return primitiveDefaults.get(type); } }
Defaults { public static Object defaultValueFor(@Nullable Class<?> type) { if (type == null) { return null; } return primitiveDefaults.get(type); } }
Defaults { public static Object defaultValueFor(@Nullable Class<?> type) { if (type == null) { return null; } return primitiveDefaults.get(type); } static Object defaultValueFor(@Nullable Class<?> type); }
Defaults { public static Object defaultValueFor(@Nullable Class<?> type) { if (type == null) { return null; } return primitiveDefaults.get(type); } static Object defaultValueFor(@Nullable Class<?> type); }
@Test public void defaultValueFor_objects() { assertNull(Defaults.defaultValueFor(Integer.class)); assertNull(Defaults.defaultValueFor(Double.class)); assertNull(Defaults.defaultValueFor(Boolean.class)); assertNull(Defaults.defaultValueFor(String.class)); }
public static Object defaultValueFor(@Nullable Class<?> type) { if (type == null) { return null; } return primitiveDefaults.get(type); }
Defaults { public static Object defaultValueFor(@Nullable Class<?> type) { if (type == null) { return null; } return primitiveDefaults.get(type); } }
Defaults { public static Object defaultValueFor(@Nullable Class<?> type) { if (type == null) { return null; } return primitiveDefaults.get(type); } }
Defaults { public static Object defaultValueFor(@Nullable Class<?> type) { if (type == null) { return null; } return primitiveDefaults.get(type); } static Object defaultValueFor(@Nullable Class<?> type); }
Defaults { public static Object defaultValueFor(@Nullable Class<?> type) { if (type == null) { return null; } return primitiveDefaults.get(type); } static Object defaultValueFor(@Nullable Class<?> type); }
@Test public void buildTypeDocBase() { Optional<TypeDoc> doc = reader.buildTypeDocBase(Person.class, typeReferenceProvider, c -> null); assertTrue(doc.isPresent()); TypeDoc typeDoc = doc.get(); assertEquals("Person", typeDoc.getName()); assertEquals("Represents a person.", typeDoc.getDescription()); }
@NotNull @Override public Optional<TypeDoc> buildTypeDocBase(@NotNull Class<?> clazz, @NotNull TypeReferenceProvider typeReferenceProvider, @NotNull TemplateProvider templateProvider) { TypeDoc doc = new TypeDoc(clazz); doc.setName(clazz.getSimpleName()); doc.setDescription(JavadocHelper.getJavadocDescription(clazz).orElse(null)); return Optional.of(doc); }
JavadocTypeDocReader implements TypeDocReader { @NotNull @Override public Optional<TypeDoc> buildTypeDocBase(@NotNull Class<?> clazz, @NotNull TypeReferenceProvider typeReferenceProvider, @NotNull TemplateProvider templateProvider) { TypeDoc doc = new TypeDoc(clazz); doc.setName(clazz.getSimpleName()); doc.setDescription(JavadocHelper.getJavadocDescription(clazz).orElse(null)); return Optional.of(doc); } }
JavadocTypeDocReader implements TypeDocReader { @NotNull @Override public Optional<TypeDoc> buildTypeDocBase(@NotNull Class<?> clazz, @NotNull TypeReferenceProvider typeReferenceProvider, @NotNull TemplateProvider templateProvider) { TypeDoc doc = new TypeDoc(clazz); doc.setName(clazz.getSimpleName()); doc.setDescription(JavadocHelper.getJavadocDescription(clazz).orElse(null)); return Optional.of(doc); } }
JavadocTypeDocReader implements TypeDocReader { @NotNull @Override public Optional<TypeDoc> buildTypeDocBase(@NotNull Class<?> clazz, @NotNull TypeReferenceProvider typeReferenceProvider, @NotNull TemplateProvider templateProvider) { TypeDoc doc = new TypeDoc(clazz); doc.setName(clazz.getSimpleName()); doc.setDescription(JavadocHelper.getJavadocDescription(clazz).orElse(null)); return Optional.of(doc); } @NotNull @Override Optional<TypeDoc> buildTypeDocBase(@NotNull Class<?> clazz, @NotNull TypeReferenceProvider typeReferenceProvider, @NotNull TemplateProvider templateProvider); @NotNull @Override Optional<PropertyDoc> buildPropertyDoc(Property property, TypeDoc parentDoc, TypeReferenceProvider typeReferenceProvider); }
JavadocTypeDocReader implements TypeDocReader { @NotNull @Override public Optional<TypeDoc> buildTypeDocBase(@NotNull Class<?> clazz, @NotNull TypeReferenceProvider typeReferenceProvider, @NotNull TemplateProvider templateProvider) { TypeDoc doc = new TypeDoc(clazz); doc.setName(clazz.getSimpleName()); doc.setDescription(JavadocHelper.getJavadocDescription(clazz).orElse(null)); return Optional.of(doc); } @NotNull @Override Optional<TypeDoc> buildTypeDocBase(@NotNull Class<?> clazz, @NotNull TypeReferenceProvider typeReferenceProvider, @NotNull TemplateProvider templateProvider); @NotNull @Override Optional<PropertyDoc> buildPropertyDoc(Property property, TypeDoc parentDoc, TypeReferenceProvider typeReferenceProvider); }
@Test public void buildPropertyDoc() throws NoSuchMethodException, NoSuchFieldException { Field nameField = Person.class.getDeclaredField("name"); Field ageField = Person.class.getDeclaredField("age"); Field phoneField = Person.class.getDeclaredField("phone"); Method getName = Person.class.getDeclaredMethod("getName"); Method getAge = Person.class.getDeclaredMethod("getAge"); Method getPhone = Person.class.getDeclaredMethod("getPhone"); Property nameProp = new Property("name", String.class, getName); nameProp.setField(nameField); nameProp.setGetter(getName); Property ageProp = new Property("age", Integer.class, getAge); ageProp.setField(ageField); ageProp.setGetter(getAge); Property phoneProp = new Property("phone", String.class, getPhone); phoneProp.setField(phoneField); phoneProp.setGetter(getPhone); Optional<TypeDoc> doc = reader.buildTypeDocBase(Person.class, typeReferenceProvider, c -> null); assertTrue(doc.isPresent()); TypeDoc typeDoc = doc.get(); Optional<PropertyDoc> maybeNameDoc = reader.buildPropertyDoc(nameProp, typeDoc, typeReferenceProvider); Optional<PropertyDoc> maybeAgeDoc = reader.buildPropertyDoc(ageProp, typeDoc, typeReferenceProvider); Optional<PropertyDoc> maybePhoneDoc = reader.buildPropertyDoc(phoneProp, typeDoc, typeReferenceProvider); assertTrue(maybeNameDoc.isPresent()); assertTrue(maybeAgeDoc.isPresent()); assertTrue(maybePhoneDoc.isPresent()); PropertyDoc nameDoc = maybeNameDoc.get(); PropertyDoc ageDoc = maybeAgeDoc.get(); PropertyDoc phoneDoc = maybePhoneDoc.get(); assertEquals("name", nameDoc.getName()); assertEquals("age", ageDoc.getName()); assertEquals("phone", phoneDoc.getName()); assertEquals("The name of this <code>Person</code>.", nameDoc.getDescription()); assertEquals("this person's age", ageDoc.getDescription()); assertEquals("Gets this person's <code>phone number</code>.", phoneDoc.getDescription()); }
@NotNull @Override public Optional<PropertyDoc> buildPropertyDoc(Property property, TypeDoc parentDoc, TypeReferenceProvider typeReferenceProvider) { PropertyDoc doc = new PropertyDoc(); doc.setName(property.getName()); doc.setDescription(getPropertyDescription(property)); return Optional.of(doc); }
JavadocTypeDocReader implements TypeDocReader { @NotNull @Override public Optional<PropertyDoc> buildPropertyDoc(Property property, TypeDoc parentDoc, TypeReferenceProvider typeReferenceProvider) { PropertyDoc doc = new PropertyDoc(); doc.setName(property.getName()); doc.setDescription(getPropertyDescription(property)); return Optional.of(doc); } }
JavadocTypeDocReader implements TypeDocReader { @NotNull @Override public Optional<PropertyDoc> buildPropertyDoc(Property property, TypeDoc parentDoc, TypeReferenceProvider typeReferenceProvider) { PropertyDoc doc = new PropertyDoc(); doc.setName(property.getName()); doc.setDescription(getPropertyDescription(property)); return Optional.of(doc); } }
JavadocTypeDocReader implements TypeDocReader { @NotNull @Override public Optional<PropertyDoc> buildPropertyDoc(Property property, TypeDoc parentDoc, TypeReferenceProvider typeReferenceProvider) { PropertyDoc doc = new PropertyDoc(); doc.setName(property.getName()); doc.setDescription(getPropertyDescription(property)); return Optional.of(doc); } @NotNull @Override Optional<TypeDoc> buildTypeDocBase(@NotNull Class<?> clazz, @NotNull TypeReferenceProvider typeReferenceProvider, @NotNull TemplateProvider templateProvider); @NotNull @Override Optional<PropertyDoc> buildPropertyDoc(Property property, TypeDoc parentDoc, TypeReferenceProvider typeReferenceProvider); }
JavadocTypeDocReader implements TypeDocReader { @NotNull @Override public Optional<PropertyDoc> buildPropertyDoc(Property property, TypeDoc parentDoc, TypeReferenceProvider typeReferenceProvider) { PropertyDoc doc = new PropertyDoc(); doc.setName(property.getName()); doc.setDescription(getPropertyDescription(property)); return Optional.of(doc); } @NotNull @Override Optional<TypeDoc> buildTypeDocBase(@NotNull Class<?> clazz, @NotNull TypeReferenceProvider typeReferenceProvider, @NotNull TemplateProvider templateProvider); @NotNull @Override Optional<PropertyDoc> buildPropertyDoc(Property property, TypeDoc parentDoc, TypeReferenceProvider typeReferenceProvider); }
@Test public void getProperties_primitive() { assertTrue(scanner.getProperties(int.class).isEmpty()); }
@Override public List<Property> getProperties(Type type) { return getJacksonProperties(type).stream() .filter(JacksonPropertyScanner::isReadable) .map(this::convertProp) .collect(toList()); }
JacksonPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { return getJacksonProperties(type).stream() .filter(JacksonPropertyScanner::isReadable) .map(this::convertProp) .collect(toList()); } }
JacksonPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { return getJacksonProperties(type).stream() .filter(JacksonPropertyScanner::isReadable) .map(this::convertProp) .collect(toList()); } JacksonPropertyScanner(ObjectMapper mapper); }
JacksonPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { return getJacksonProperties(type).stream() .filter(JacksonPropertyScanner::isReadable) .map(this::convertProp) .collect(toList()); } JacksonPropertyScanner(ObjectMapper mapper); @Override List<Property> getProperties(Type type); }
JacksonPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { return getJacksonProperties(type).stream() .filter(JacksonPropertyScanner::isReadable) .map(this::convertProp) .collect(toList()); } JacksonPropertyScanner(ObjectMapper mapper); @Override List<Property> getProperties(Type type); }
@Test public void testLoadUserByUsername() { server.expect(requestTo("/" + USERNAME)).andExpect(method(GET)) .andRespond(withHalJsonResponse("/user_jbloggs_GET.txt")); UserDetails userDetails = service.loadUserByUsername(USERNAME); assertNotNull(userDetails); }
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return restTemplate.getForObject("/{0}", User.class, username); }
RestUserDetailsService implements UserDetailsManager { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return restTemplate.getForObject("/{0}", User.class, username); } }
RestUserDetailsService implements UserDetailsManager { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return restTemplate.getForObject("/{0}", User.class, username); } RestUserDetailsService(RestTemplateBuilder builder, @Value("${app.service.url.users}") String rootUri); }
RestUserDetailsService implements UserDetailsManager { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return restTemplate.getForObject("/{0}", User.class, username); } RestUserDetailsService(RestTemplateBuilder builder, @Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); }
RestUserDetailsService implements UserDetailsManager { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return restTemplate.getForObject("/{0}", User.class, username); } RestUserDetailsService(RestTemplateBuilder builder, @Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); }
@Test public void testCreate() throws Exception { server.expect(requestTo("/")).andExpect(method(POST)) .andRespond(withStatus(HttpStatus.CREATED)); Spanner newSpanner = aSpanner().withId(null).build(); service.create(newSpanner); server.verify(); }
public void create(Spanner spanner) { restTemplate.postForObject("/", spanner, Spanner.class); }
SpannersService { public void create(Spanner spanner) { restTemplate.postForObject("/", spanner, Spanner.class); } }
SpannersService { public void create(Spanner spanner) { restTemplate.postForObject("/", spanner, Spanner.class); } SpannersService(RestTemplateBuilder builder, @Value("${app.service.url.spanners}") String rootUri); }
SpannersService { public void create(Spanner spanner) { restTemplate.postForObject("/", spanner, Spanner.class); } SpannersService(RestTemplateBuilder builder, @Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Spanner findOne(Long id); @PreAuthorize("hasPermission(#spanner, 'owner')") void delete(Spanner spanner); void create(Spanner spanner); @PreAuthorize("hasPermission(#spanner, 'owner')") void update(Spanner spanner); }
SpannersService { public void create(Spanner spanner) { restTemplate.postForObject("/", spanner, Spanner.class); } SpannersService(RestTemplateBuilder builder, @Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Spanner findOne(Long id); @PreAuthorize("hasPermission(#spanner, 'owner')") void delete(Spanner spanner); void create(Spanner spanner); @PreAuthorize("hasPermission(#spanner, 'owner')") void update(Spanner spanner); }
@Test public void testUpdate() throws Exception { server.expect(requestTo("/1")).andExpect(method(PUT)) .andRespond(withStatus(HttpStatus.OK)); Spanner update = aSpanner().withId(1L).build(); service.update(update); server.verify(); }
@PreAuthorize("hasPermission(#spanner, 'owner')") public void update(Spanner spanner) { restTemplate.put("/{0}", spanner, spanner.getId()); }
SpannersService { @PreAuthorize("hasPermission(#spanner, 'owner')") public void update(Spanner spanner) { restTemplate.put("/{0}", spanner, spanner.getId()); } }
SpannersService { @PreAuthorize("hasPermission(#spanner, 'owner')") public void update(Spanner spanner) { restTemplate.put("/{0}", spanner, spanner.getId()); } SpannersService(RestTemplateBuilder builder, @Value("${app.service.url.spanners}") String rootUri); }
SpannersService { @PreAuthorize("hasPermission(#spanner, 'owner')") public void update(Spanner spanner) { restTemplate.put("/{0}", spanner, spanner.getId()); } SpannersService(RestTemplateBuilder builder, @Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Spanner findOne(Long id); @PreAuthorize("hasPermission(#spanner, 'owner')") void delete(Spanner spanner); void create(Spanner spanner); @PreAuthorize("hasPermission(#spanner, 'owner')") void update(Spanner spanner); }
SpannersService { @PreAuthorize("hasPermission(#spanner, 'owner')") public void update(Spanner spanner) { restTemplate.put("/{0}", spanner, spanner.getId()); } SpannersService(RestTemplateBuilder builder, @Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Spanner findOne(Long id); @PreAuthorize("hasPermission(#spanner, 'owner')") void delete(Spanner spanner); void create(Spanner spanner); @PreAuthorize("hasPermission(#spanner, 'owner')") void update(Spanner spanner); }
@Test public void testPageDisplay() { ModelAndView response = controller.displayPage(); assertNotNull("no response", response); assertEquals("view", VIEW_ADD_SPANNER, response.getViewName()); }
@RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage() { SpannerForm newSpanner = new SpannerForm(); return new ModelAndView(VIEW_ADD_SPANNER, MODEL_SPANNER, newSpanner); }
AddSpannerController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage() { SpannerForm newSpanner = new SpannerForm(); return new ModelAndView(VIEW_ADD_SPANNER, MODEL_SPANNER, newSpanner); } }
AddSpannerController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage() { SpannerForm newSpanner = new SpannerForm(); return new ModelAndView(VIEW_ADD_SPANNER, MODEL_SPANNER, newSpanner); } }
AddSpannerController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage() { SpannerForm newSpanner = new SpannerForm(); return new ModelAndView(VIEW_ADD_SPANNER, MODEL_SPANNER, newSpanner); } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) ModelAndView displayPage(); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) ModelAndView addSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult, Principal principal); }
AddSpannerController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage() { SpannerForm newSpanner = new SpannerForm(); return new ModelAndView(VIEW_ADD_SPANNER, MODEL_SPANNER, newSpanner); } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) ModelAndView displayPage(); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) ModelAndView addSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult, Principal principal); static final String CONTROLLER_URL; static final String VIEW_ADD_SPANNER; static final String VIEW_SUCCESS; static final String VIEW_VALIDATION_FAIL; static final String MODEL_SPANNER; }
@Test public void testAddSpanner() { SpannerForm formData = new SpannerForm(); formData.setName("Keeley"); formData.setSize(12); Principal currentUser = new TestingAuthenticationToken("user", "pass"); BindingResult noErrors = new BeanPropertyBindingResult(formData, MODEL_SPANNER); ModelAndView response = controller.addSpanner(formData, noErrors, currentUser); assertNotNull("no response", response); ArgumentCaptor<Spanner> spannerArgumentCaptor = ArgumentCaptor.forClass(Spanner.class); verify(spannersService).create(spannerArgumentCaptor.capture()); Spanner createdSpanner = spannerArgumentCaptor.getValue(); assertEquals("name", formData.getName(), createdSpanner.getName()); assertEquals("size", formData.getSize(), createdSpanner.getSize()); assertEquals("owner", currentUser.getName(), createdSpanner.getOwner()); assertEquals("view", VIEW_SUCCESS, response.getViewName()); }
@RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public ModelAndView addSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult, Principal principal) { if (validationResult.hasErrors()) { return new ModelAndView(VIEW_VALIDATION_FAIL); } Spanner spanner = new Spanner(); spanner.setOwner(principal.getName()); spanner.setName(formData.getName()); spanner.setSize(formData.getSize()); spannersService.create(spanner); return new ModelAndView(VIEW_SUCCESS); }
AddSpannerController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public ModelAndView addSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult, Principal principal) { if (validationResult.hasErrors()) { return new ModelAndView(VIEW_VALIDATION_FAIL); } Spanner spanner = new Spanner(); spanner.setOwner(principal.getName()); spanner.setName(formData.getName()); spanner.setSize(formData.getSize()); spannersService.create(spanner); return new ModelAndView(VIEW_SUCCESS); } }
AddSpannerController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public ModelAndView addSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult, Principal principal) { if (validationResult.hasErrors()) { return new ModelAndView(VIEW_VALIDATION_FAIL); } Spanner spanner = new Spanner(); spanner.setOwner(principal.getName()); spanner.setName(formData.getName()); spanner.setSize(formData.getSize()); spannersService.create(spanner); return new ModelAndView(VIEW_SUCCESS); } }
AddSpannerController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public ModelAndView addSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult, Principal principal) { if (validationResult.hasErrors()) { return new ModelAndView(VIEW_VALIDATION_FAIL); } Spanner spanner = new Spanner(); spanner.setOwner(principal.getName()); spanner.setName(formData.getName()); spanner.setSize(formData.getSize()); spannersService.create(spanner); return new ModelAndView(VIEW_SUCCESS); } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) ModelAndView displayPage(); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) ModelAndView addSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult, Principal principal); }
AddSpannerController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public ModelAndView addSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult, Principal principal) { if (validationResult.hasErrors()) { return new ModelAndView(VIEW_VALIDATION_FAIL); } Spanner spanner = new Spanner(); spanner.setOwner(principal.getName()); spanner.setName(formData.getName()); spanner.setSize(formData.getSize()); spannersService.create(spanner); return new ModelAndView(VIEW_SUCCESS); } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) ModelAndView displayPage(); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) ModelAndView addSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult, Principal principal); static final String CONTROLLER_URL; static final String VIEW_ADD_SPANNER; static final String VIEW_SUCCESS; static final String VIEW_VALIDATION_FAIL; static final String MODEL_SPANNER; }
@Test public void testValidationFail() { SpannerForm formData = new SpannerForm(); formData.setName("Keeley"); formData.setSize(12); BindingResult validationFail = new BeanPropertyBindingResult(formData, MODEL_SPANNER); validationFail.addError(new ObjectError("size", "TOO_BIG")); Principal currentUser = new TestingAuthenticationToken("user", "pass"); ModelAndView response = controller.addSpanner(formData, validationFail, currentUser); assertNotNull("no response", response); verify(spannersService, never()).update(any(Spanner.class)); assertEquals("view", VIEW_VALIDATION_FAIL, response.getViewName()); }
@RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public ModelAndView addSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult, Principal principal) { if (validationResult.hasErrors()) { return new ModelAndView(VIEW_VALIDATION_FAIL); } Spanner spanner = new Spanner(); spanner.setOwner(principal.getName()); spanner.setName(formData.getName()); spanner.setSize(formData.getSize()); spannersService.create(spanner); return new ModelAndView(VIEW_SUCCESS); }
AddSpannerController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public ModelAndView addSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult, Principal principal) { if (validationResult.hasErrors()) { return new ModelAndView(VIEW_VALIDATION_FAIL); } Spanner spanner = new Spanner(); spanner.setOwner(principal.getName()); spanner.setName(formData.getName()); spanner.setSize(formData.getSize()); spannersService.create(spanner); return new ModelAndView(VIEW_SUCCESS); } }
AddSpannerController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public ModelAndView addSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult, Principal principal) { if (validationResult.hasErrors()) { return new ModelAndView(VIEW_VALIDATION_FAIL); } Spanner spanner = new Spanner(); spanner.setOwner(principal.getName()); spanner.setName(formData.getName()); spanner.setSize(formData.getSize()); spannersService.create(spanner); return new ModelAndView(VIEW_SUCCESS); } }
AddSpannerController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public ModelAndView addSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult, Principal principal) { if (validationResult.hasErrors()) { return new ModelAndView(VIEW_VALIDATION_FAIL); } Spanner spanner = new Spanner(); spanner.setOwner(principal.getName()); spanner.setName(formData.getName()); spanner.setSize(formData.getSize()); spannersService.create(spanner); return new ModelAndView(VIEW_SUCCESS); } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) ModelAndView displayPage(); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) ModelAndView addSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult, Principal principal); }
AddSpannerController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public ModelAndView addSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult, Principal principal) { if (validationResult.hasErrors()) { return new ModelAndView(VIEW_VALIDATION_FAIL); } Spanner spanner = new Spanner(); spanner.setOwner(principal.getName()); spanner.setName(formData.getName()); spanner.setSize(formData.getSize()); spannersService.create(spanner); return new ModelAndView(VIEW_SUCCESS); } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) ModelAndView displayPage(); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) ModelAndView addSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult, Principal principal); static final String CONTROLLER_URL; static final String VIEW_ADD_SPANNER; static final String VIEW_SUCCESS; static final String VIEW_VALIDATION_FAIL; static final String MODEL_SPANNER; }
@Test public void testDisplayPage() throws Exception { when(spannersService.findOne(SPANNER_ID)).thenReturn(SPANNER); ModelAndView response = controller.displayDetail(SPANNER_ID); assertNotNull("no response", response); assertEquals(VIEW_DETAIL_SPANNER, response.getViewName()); Spanner spannerInModel = (Spanner)response.getModelMap().get(MODEL_SPANNER); assertSpannerEquals(SPANNER, spannerInModel); }
@RequestMapping(value = "/detailSpanner", method = RequestMethod.GET) public ModelAndView displayDetail(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } return new ModelAndView(VIEW_DETAIL_SPANNER, MODEL_SPANNER, spanner); }
DetailSpannerController { @RequestMapping(value = "/detailSpanner", method = RequestMethod.GET) public ModelAndView displayDetail(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } return new ModelAndView(VIEW_DETAIL_SPANNER, MODEL_SPANNER, spanner); } }
DetailSpannerController { @RequestMapping(value = "/detailSpanner", method = RequestMethod.GET) public ModelAndView displayDetail(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } return new ModelAndView(VIEW_DETAIL_SPANNER, MODEL_SPANNER, spanner); } }
DetailSpannerController { @RequestMapping(value = "/detailSpanner", method = RequestMethod.GET) public ModelAndView displayDetail(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } return new ModelAndView(VIEW_DETAIL_SPANNER, MODEL_SPANNER, spanner); } @RequestMapping(value = "/detailSpanner", method = RequestMethod.GET) ModelAndView displayDetail(@RequestParam Long id); }
DetailSpannerController { @RequestMapping(value = "/detailSpanner", method = RequestMethod.GET) public ModelAndView displayDetail(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } return new ModelAndView(VIEW_DETAIL_SPANNER, MODEL_SPANNER, spanner); } @RequestMapping(value = "/detailSpanner", method = RequestMethod.GET) ModelAndView displayDetail(@RequestParam Long id); static final String VIEW_DETAIL_SPANNER; static final String MODEL_SPANNER; }
@Test public void testSpannerNotFound() throws Exception { when(spannersService.findOne(SPANNER_ID)).thenReturn(null); try { controller.displayDetail(SPANNER_ID); fail("Expected: SpannerNotFoundException"); } catch(SpannerNotFoundException notFoundEx) { assertEquals("Exception spanner id", SPANNER_ID, notFoundEx.getSpannerId()); } }
@RequestMapping(value = "/detailSpanner", method = RequestMethod.GET) public ModelAndView displayDetail(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } return new ModelAndView(VIEW_DETAIL_SPANNER, MODEL_SPANNER, spanner); }
DetailSpannerController { @RequestMapping(value = "/detailSpanner", method = RequestMethod.GET) public ModelAndView displayDetail(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } return new ModelAndView(VIEW_DETAIL_SPANNER, MODEL_SPANNER, spanner); } }
DetailSpannerController { @RequestMapping(value = "/detailSpanner", method = RequestMethod.GET) public ModelAndView displayDetail(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } return new ModelAndView(VIEW_DETAIL_SPANNER, MODEL_SPANNER, spanner); } }
DetailSpannerController { @RequestMapping(value = "/detailSpanner", method = RequestMethod.GET) public ModelAndView displayDetail(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } return new ModelAndView(VIEW_DETAIL_SPANNER, MODEL_SPANNER, spanner); } @RequestMapping(value = "/detailSpanner", method = RequestMethod.GET) ModelAndView displayDetail(@RequestParam Long id); }
DetailSpannerController { @RequestMapping(value = "/detailSpanner", method = RequestMethod.GET) public ModelAndView displayDetail(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } return new ModelAndView(VIEW_DETAIL_SPANNER, MODEL_SPANNER, spanner); } @RequestMapping(value = "/detailSpanner", method = RequestMethod.GET) ModelAndView displayDetail(@RequestParam Long id); static final String VIEW_DETAIL_SPANNER; static final String MODEL_SPANNER; }
@Test public void testHomePage() { String response = controller.index(); assertEquals("view name", VIEW_NOT_SIGNED_IN, response); }
@RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String index() { return VIEW_NOT_SIGNED_IN; }
HomeController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String index() { return VIEW_NOT_SIGNED_IN; } }
HomeController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String index() { return VIEW_NOT_SIGNED_IN; } }
HomeController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String index() { return VIEW_NOT_SIGNED_IN; } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) String index(); }
HomeController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String index() { return VIEW_NOT_SIGNED_IN; } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) String index(); static final String CONTROLLER_URL; static final String VIEW_NOT_SIGNED_IN; }
@Test public void testSuccessForward() { SignupForm form = populateForm(NAME, PASSWORD); Errors noErrors = new DirectFieldBindingResult(form, "form"); String response = controller.signup(form, noErrors); assertEquals(SignupController.VIEW_SUCCESS, response); }
@RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; }
SignupController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; } }
SignupController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; } }
SignupController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; } @RequestMapping(value = CONTROLLER_URL) SignupForm displayPage(); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors); }
SignupController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; } @RequestMapping(value = CONTROLLER_URL) SignupForm displayPage(); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors); static final String CONTROLLER_URL; static final String VIEW_SUCCESS; }
@Test public void testAccountCreation() { SignupForm form = populateForm(NAME, PASSWORD); Errors noErrors = new DirectFieldBindingResult(form, "form"); controller.signup(form, noErrors); verify(userDetailsManager).createUser(argThat(hasProperty("username", equalTo(NAME)))); }
@RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; }
SignupController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; } }
SignupController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; } }
SignupController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; } @RequestMapping(value = CONTROLLER_URL) SignupForm displayPage(); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors); }
SignupController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; } @RequestMapping(value = CONTROLLER_URL) SignupForm displayPage(); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors); static final String CONTROLLER_URL; static final String VIEW_SUCCESS; }
@Test public void testCreateUser() throws Exception { server.expect(requestTo("/")).andExpect(method(POST)) .andRespond(withStatus(HttpStatus.CREATED)); UserDetails user = new User(USERNAME, PASSWORD, ENABLED); service.createUser(user); server.verify(); }
@Override public void createUser(UserDetails userDetails) { restTemplate.postForLocation("/", userDetails); }
RestUserDetailsService implements UserDetailsManager { @Override public void createUser(UserDetails userDetails) { restTemplate.postForLocation("/", userDetails); } }
RestUserDetailsService implements UserDetailsManager { @Override public void createUser(UserDetails userDetails) { restTemplate.postForLocation("/", userDetails); } RestUserDetailsService(RestTemplateBuilder builder, @Value("${app.service.url.users}") String rootUri); }
RestUserDetailsService implements UserDetailsManager { @Override public void createUser(UserDetails userDetails) { restTemplate.postForLocation("/", userDetails); } RestUserDetailsService(RestTemplateBuilder builder, @Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); }
RestUserDetailsService implements UserDetailsManager { @Override public void createUser(UserDetails userDetails) { restTemplate.postForLocation("/", userDetails); } RestUserDetailsService(RestTemplateBuilder builder, @Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); }
@Test public void testPasswordHash() { given(passwordEncoder.encode(PASSWORD)).willReturn(HASHED_PASSWORD); SignupForm form = populateForm(NAME, PASSWORD); Errors noErrors = new DirectFieldBindingResult(form, "form"); controller.signup(form, noErrors); verify(userDetailsManager).createUser(argThat(hasProperty("password", equalTo(HASHED_PASSWORD)))); }
@RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; }
SignupController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; } }
SignupController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; } }
SignupController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; } @RequestMapping(value = CONTROLLER_URL) SignupForm displayPage(); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors); }
SignupController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; } @RequestMapping(value = CONTROLLER_URL) SignupForm displayPage(); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors); static final String CONTROLLER_URL; static final String VIEW_SUCCESS; }
@Test public void testValidationFailIsLogged() { SignupForm invalidForm = populateForm(null, null); Errors errors = new DirectFieldBindingResult(invalidForm, "form"); errors.rejectValue("name", "Invalid name"); errors.rejectValue("password", "Invalid password"); controller.signup(invalidForm, errors); assertThat(sysOut.asString(), containsString("Oh no!")); }
@RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; }
SignupController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; } }
SignupController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; } }
SignupController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; } @RequestMapping(value = CONTROLLER_URL) SignupForm displayPage(); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors); }
SignupController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; } @RequestMapping(value = CONTROLLER_URL) SignupForm displayPage(); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors); static final String CONTROLLER_URL; static final String VIEW_SUCCESS; }
@Test public void testSuccessIsLogged() { SignupForm form = populateForm(NAME, PASSWORD); Errors noErrors = new DirectFieldBindingResult(form, "form"); controller.signup(form, noErrors); assertThat(sysOut.asString(), containsString("Success!")); }
@RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; }
SignupController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; } }
SignupController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; } }
SignupController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; } @RequestMapping(value = CONTROLLER_URL) SignupForm displayPage(); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors); }
SignupController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; } @RequestMapping(value = CONTROLLER_URL) SignupForm displayPage(); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors); static final String CONTROLLER_URL; static final String VIEW_SUCCESS; }
@Test public void testDisplaySpanners() { when(spannersService.findAll()).thenReturn(SPANNERS); ModelMap model = new ModelMap(); String view = controller.displaySpanners(model); assertEquals("view name", VIEW_DISPLAY_SPANNERS, view); @SuppressWarnings("unchecked") List<Spanner> spannersInModel = (List<Spanner>)model.get(MODEL_ATTRIBUTE_SPANNERS); assertNotNull(MODEL_ATTRIBUTE_SPANNERS + " is null", spannersInModel); assertEquals(SPANNERS, spannersInModel); }
@RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { Collection<Spanner> spanners = spannersService.findAll(); String greeting = timeOfDayGreeting(); model.addAttribute(MODEL_ATTRIBUTE_SPANNERS, spanners); model.addAttribute(MODEL_ATTRIBUTE_GREETING, greeting); return VIEW_DISPLAY_SPANNERS; }
DisplaySpannersController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { Collection<Spanner> spanners = spannersService.findAll(); String greeting = timeOfDayGreeting(); model.addAttribute(MODEL_ATTRIBUTE_SPANNERS, spanners); model.addAttribute(MODEL_ATTRIBUTE_GREETING, greeting); return VIEW_DISPLAY_SPANNERS; } }
DisplaySpannersController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { Collection<Spanner> spanners = spannersService.findAll(); String greeting = timeOfDayGreeting(); model.addAttribute(MODEL_ATTRIBUTE_SPANNERS, spanners); model.addAttribute(MODEL_ATTRIBUTE_GREETING, greeting); return VIEW_DISPLAY_SPANNERS; } }
DisplaySpannersController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { Collection<Spanner> spanners = spannersService.findAll(); String greeting = timeOfDayGreeting(); model.addAttribute(MODEL_ATTRIBUTE_SPANNERS, spanners); model.addAttribute(MODEL_ATTRIBUTE_GREETING, greeting); return VIEW_DISPLAY_SPANNERS; } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) String displaySpanners(ModelMap model); @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) String deleteSpanner(@RequestParam Long id, ModelMap model); }
DisplaySpannersController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { Collection<Spanner> spanners = spannersService.findAll(); String greeting = timeOfDayGreeting(); model.addAttribute(MODEL_ATTRIBUTE_SPANNERS, spanners); model.addAttribute(MODEL_ATTRIBUTE_GREETING, greeting); return VIEW_DISPLAY_SPANNERS; } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) String displaySpanners(ModelMap model); @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) String deleteSpanner(@RequestParam Long id, ModelMap model); }
@Test public void testTimeOfDayGreetingMorning() { when(currentTime.get()).thenReturn(LocalTime.of(9,0)); ModelMap model = new ModelMap(); controller.displaySpanners(model); String greeting = (String)model.get(MODEL_ATTRIBUTE_GREETING); assertEquals(GREETING_MORNING, greeting); }
@RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { Collection<Spanner> spanners = spannersService.findAll(); String greeting = timeOfDayGreeting(); model.addAttribute(MODEL_ATTRIBUTE_SPANNERS, spanners); model.addAttribute(MODEL_ATTRIBUTE_GREETING, greeting); return VIEW_DISPLAY_SPANNERS; }
DisplaySpannersController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { Collection<Spanner> spanners = spannersService.findAll(); String greeting = timeOfDayGreeting(); model.addAttribute(MODEL_ATTRIBUTE_SPANNERS, spanners); model.addAttribute(MODEL_ATTRIBUTE_GREETING, greeting); return VIEW_DISPLAY_SPANNERS; } }
DisplaySpannersController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { Collection<Spanner> spanners = spannersService.findAll(); String greeting = timeOfDayGreeting(); model.addAttribute(MODEL_ATTRIBUTE_SPANNERS, spanners); model.addAttribute(MODEL_ATTRIBUTE_GREETING, greeting); return VIEW_DISPLAY_SPANNERS; } }
DisplaySpannersController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { Collection<Spanner> spanners = spannersService.findAll(); String greeting = timeOfDayGreeting(); model.addAttribute(MODEL_ATTRIBUTE_SPANNERS, spanners); model.addAttribute(MODEL_ATTRIBUTE_GREETING, greeting); return VIEW_DISPLAY_SPANNERS; } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) String displaySpanners(ModelMap model); @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) String deleteSpanner(@RequestParam Long id, ModelMap model); }
DisplaySpannersController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { Collection<Spanner> spanners = spannersService.findAll(); String greeting = timeOfDayGreeting(); model.addAttribute(MODEL_ATTRIBUTE_SPANNERS, spanners); model.addAttribute(MODEL_ATTRIBUTE_GREETING, greeting); return VIEW_DISPLAY_SPANNERS; } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) String displaySpanners(ModelMap model); @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) String deleteSpanner(@RequestParam Long id, ModelMap model); }
@Test public void testTimeOfDayGreetingAfternoon() { when(currentTime.get()).thenReturn(LocalTime.of(14,0)); ModelMap model = new ModelMap(); controller.displaySpanners(model); String greeting = (String)model.get(MODEL_ATTRIBUTE_GREETING); assertEquals(GREETING_AFTERNOON, greeting); }
@RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { Collection<Spanner> spanners = spannersService.findAll(); String greeting = timeOfDayGreeting(); model.addAttribute(MODEL_ATTRIBUTE_SPANNERS, spanners); model.addAttribute(MODEL_ATTRIBUTE_GREETING, greeting); return VIEW_DISPLAY_SPANNERS; }
DisplaySpannersController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { Collection<Spanner> spanners = spannersService.findAll(); String greeting = timeOfDayGreeting(); model.addAttribute(MODEL_ATTRIBUTE_SPANNERS, spanners); model.addAttribute(MODEL_ATTRIBUTE_GREETING, greeting); return VIEW_DISPLAY_SPANNERS; } }
DisplaySpannersController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { Collection<Spanner> spanners = spannersService.findAll(); String greeting = timeOfDayGreeting(); model.addAttribute(MODEL_ATTRIBUTE_SPANNERS, spanners); model.addAttribute(MODEL_ATTRIBUTE_GREETING, greeting); return VIEW_DISPLAY_SPANNERS; } }
DisplaySpannersController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { Collection<Spanner> spanners = spannersService.findAll(); String greeting = timeOfDayGreeting(); model.addAttribute(MODEL_ATTRIBUTE_SPANNERS, spanners); model.addAttribute(MODEL_ATTRIBUTE_GREETING, greeting); return VIEW_DISPLAY_SPANNERS; } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) String displaySpanners(ModelMap model); @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) String deleteSpanner(@RequestParam Long id, ModelMap model); }
DisplaySpannersController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { Collection<Spanner> spanners = spannersService.findAll(); String greeting = timeOfDayGreeting(); model.addAttribute(MODEL_ATTRIBUTE_SPANNERS, spanners); model.addAttribute(MODEL_ATTRIBUTE_GREETING, greeting); return VIEW_DISPLAY_SPANNERS; } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) String displaySpanners(ModelMap model); @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) String deleteSpanner(@RequestParam Long id, ModelMap model); }
@Test public void testTimeOfDayGreetingEvening() { when(currentTime.get()).thenReturn(LocalTime.of(20,0)); ModelMap model = new ModelMap(); controller.displaySpanners(model); String greeting = (String)model.get(MODEL_ATTRIBUTE_GREETING); assertEquals(GREETING_EVENING, greeting); }
@RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { Collection<Spanner> spanners = spannersService.findAll(); String greeting = timeOfDayGreeting(); model.addAttribute(MODEL_ATTRIBUTE_SPANNERS, spanners); model.addAttribute(MODEL_ATTRIBUTE_GREETING, greeting); return VIEW_DISPLAY_SPANNERS; }
DisplaySpannersController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { Collection<Spanner> spanners = spannersService.findAll(); String greeting = timeOfDayGreeting(); model.addAttribute(MODEL_ATTRIBUTE_SPANNERS, spanners); model.addAttribute(MODEL_ATTRIBUTE_GREETING, greeting); return VIEW_DISPLAY_SPANNERS; } }
DisplaySpannersController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { Collection<Spanner> spanners = spannersService.findAll(); String greeting = timeOfDayGreeting(); model.addAttribute(MODEL_ATTRIBUTE_SPANNERS, spanners); model.addAttribute(MODEL_ATTRIBUTE_GREETING, greeting); return VIEW_DISPLAY_SPANNERS; } }
DisplaySpannersController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { Collection<Spanner> spanners = spannersService.findAll(); String greeting = timeOfDayGreeting(); model.addAttribute(MODEL_ATTRIBUTE_SPANNERS, spanners); model.addAttribute(MODEL_ATTRIBUTE_GREETING, greeting); return VIEW_DISPLAY_SPANNERS; } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) String displaySpanners(ModelMap model); @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) String deleteSpanner(@RequestParam Long id, ModelMap model); }
DisplaySpannersController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { Collection<Spanner> spanners = spannersService.findAll(); String greeting = timeOfDayGreeting(); model.addAttribute(MODEL_ATTRIBUTE_SPANNERS, spanners); model.addAttribute(MODEL_ATTRIBUTE_GREETING, greeting); return VIEW_DISPLAY_SPANNERS; } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) String displaySpanners(ModelMap model); @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) String deleteSpanner(@RequestParam Long id, ModelMap model); }
@Test public void testDeleteSpanner() throws Exception { when(spannersService.findOne(SPANNER_ID)).thenReturn(SPANNER); ModelMap model = new ModelMap(); String view = controller.deleteSpanner(SPANNER_ID, model); verify(spannersService).delete(SPANNER); assertEquals("view name", VIEW_DISPLAY_SPANNERS, view); }
@RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) public String deleteSpanner(@RequestParam Long id, ModelMap model) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } spannersService.delete(spanner); return displaySpanners(model); }
DisplaySpannersController { @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) public String deleteSpanner(@RequestParam Long id, ModelMap model) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } spannersService.delete(spanner); return displaySpanners(model); } }
DisplaySpannersController { @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) public String deleteSpanner(@RequestParam Long id, ModelMap model) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } spannersService.delete(spanner); return displaySpanners(model); } }
DisplaySpannersController { @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) public String deleteSpanner(@RequestParam Long id, ModelMap model) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } spannersService.delete(spanner); return displaySpanners(model); } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) String displaySpanners(ModelMap model); @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) String deleteSpanner(@RequestParam Long id, ModelMap model); }
DisplaySpannersController { @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) public String deleteSpanner(@RequestParam Long id, ModelMap model) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } spannersService.delete(spanner); return displaySpanners(model); } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) String displaySpanners(ModelMap model); @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) String deleteSpanner(@RequestParam Long id, ModelMap model); }
@Test public void testDeleteSpannerNotFound() { when(spannersService.findOne(SPANNER_ID)).thenReturn(null); try { controller.deleteSpanner(SPANNER_ID, new ModelMap()); fail("Expected: SpannerNotFoundException"); } catch(SpannerNotFoundException notFoundEx) { assertEquals("Exception spanner id", SPANNER_ID, notFoundEx.getSpannerId()); } }
@RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) public String deleteSpanner(@RequestParam Long id, ModelMap model) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } spannersService.delete(spanner); return displaySpanners(model); }
DisplaySpannersController { @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) public String deleteSpanner(@RequestParam Long id, ModelMap model) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } spannersService.delete(spanner); return displaySpanners(model); } }
DisplaySpannersController { @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) public String deleteSpanner(@RequestParam Long id, ModelMap model) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } spannersService.delete(spanner); return displaySpanners(model); } }
DisplaySpannersController { @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) public String deleteSpanner(@RequestParam Long id, ModelMap model) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } spannersService.delete(spanner); return displaySpanners(model); } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) String displaySpanners(ModelMap model); @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) String deleteSpanner(@RequestParam Long id, ModelMap model); }
DisplaySpannersController { @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) public String deleteSpanner(@RequestParam Long id, ModelMap model) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } spannersService.delete(spanner); return displaySpanners(model); } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) String displaySpanners(ModelMap model); @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) String deleteSpanner(@RequestParam Long id, ModelMap model); }