Refactor Reflection examples

This commit is contained in:
Grzegorz Piwowarek 2016-09-04 08:18:17 +02:00
parent 89944e9a9f
commit 6bd09ce0ae
8 changed files with 342 additions and 330 deletions

View File

@ -12,8 +12,8 @@
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version> <version>3.3</version>
<configuration> <configuration>
<source>7</source> <source>8</source>
<target>7</target> <target>8</target>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>

View File

@ -1,7 +1,9 @@
package com.baeldung.reflection; package com.baeldung.reflection;
public abstract class Animal implements Eating { public abstract class Animal implements Eating {
public static final String CATEGORY = "domestic"; public static final String CATEGORY = "domestic";
private String name; private String name;
public Animal(String name) { public Animal(String name) {

View File

@ -2,13 +2,16 @@ package com.baeldung.reflection;
public class Bird extends Animal { public class Bird extends Animal {
private boolean walks; private boolean walks;
public Bird() { public Bird() {
super("bird"); super("bird");
} }
public Bird(String name, boolean walks) { public Bird(String name, boolean walks) {
super(name); super(name);
setWalks(walks); setWalks(walks);
} }
public Bird(String name) { public Bird(String name) {
super(name); super(name);
} }

View File

@ -1,27 +1,26 @@
package com.baeldung.reflection; package com.baeldung.reflection;
import static org.junit.Assert.*;
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test; import org.junit.Test;
import java.lang.reflect.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
import static org.junit.Assert.*;
public class ReflectionTest { public class ReflectionTest {
@Test @Test
public void givenObject_whenGetsFieldNamesAtRuntime_thenCorrect() { public void givenObject_whenGetsFieldNamesAtRuntime_thenCorrect() {
Object person = new Person(); Object person = new Person();
Field[] fields = person.getClass().getDeclaredFields(); Field[] fields = person.getClass().getDeclaredFields();
List<String> expectedFieldNames = Arrays.asList(new String[] { "name",
"age" });
List<String> actualFieldNames = new ArrayList<>(); List<String> actualFieldNames = getFieldNames(fields);
for (Field field : fields)
actualFieldNames.add(field.getName());
assertTrue(expectedFieldNames.containsAll(actualFieldNames)); assertTrue(Arrays.asList("name", "age")
.containsAll(actualFieldNames));
} }
@ -29,6 +28,7 @@ public class ReflectionTest {
public void givenObject_whenGetsClassName_thenCorrect() { public void givenObject_whenGetsClassName_thenCorrect() {
Object goat = new Goat("goat"); Object goat = new Goat("goat");
Class<?> clazz = goat.getClass(); Class<?> clazz = goat.getClass();
assertEquals("Goat", clazz.getSimpleName()); assertEquals("Goat", clazz.getSimpleName());
assertEquals("com.baeldung.reflection.Goat", clazz.getName()); assertEquals("com.baeldung.reflection.Goat", clazz.getName());
assertEquals("com.baeldung.reflection.Goat", clazz.getCanonicalName()); assertEquals("com.baeldung.reflection.Goat", clazz.getCanonicalName());
@ -38,6 +38,7 @@ public class ReflectionTest {
public void givenClassName_whenCreatesObject_thenCorrect() public void givenClassName_whenCreatesObject_thenCorrect()
throws ClassNotFoundException { throws ClassNotFoundException {
Class<?> clazz = Class.forName("com.baeldung.reflection.Goat"); Class<?> clazz = Class.forName("com.baeldung.reflection.Goat");
assertEquals("Goat", clazz.getSimpleName()); assertEquals("Goat", clazz.getSimpleName());
assertEquals("com.baeldung.reflection.Goat", clazz.getName()); assertEquals("com.baeldung.reflection.Goat", clazz.getName());
assertEquals("com.baeldung.reflection.Goat", clazz.getCanonicalName()); assertEquals("com.baeldung.reflection.Goat", clazz.getCanonicalName());
@ -50,6 +51,7 @@ public class ReflectionTest {
Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal"); Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal");
int goatMods = goatClass.getModifiers(); int goatMods = goatClass.getModifiers();
int animalMods = animalClass.getModifiers(); int animalMods = animalClass.getModifiers();
assertTrue(Modifier.isPublic(goatMods)); assertTrue(Modifier.isPublic(goatMods));
assertTrue(Modifier.isAbstract(animalMods)); assertTrue(Modifier.isAbstract(animalMods));
assertTrue(Modifier.isPublic(animalMods)); assertTrue(Modifier.isPublic(animalMods));
@ -60,6 +62,7 @@ public class ReflectionTest {
Goat goat = new Goat("goat"); Goat goat = new Goat("goat");
Class<?> goatClass = goat.getClass(); Class<?> goatClass = goat.getClass();
Package pkg = goatClass.getPackage(); Package pkg = goatClass.getPackage();
assertEquals("com.baeldung.reflection", pkg.getName()); assertEquals("com.baeldung.reflection", pkg.getName());
} }
@ -83,6 +86,7 @@ public class ReflectionTest {
Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal"); Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal");
Class<?>[] goatInterfaces = goatClass.getInterfaces(); Class<?>[] goatInterfaces = goatClass.getInterfaces();
Class<?>[] animalInterfaces = animalClass.getInterfaces(); Class<?>[] animalInterfaces = animalClass.getInterfaces();
assertEquals(1, goatInterfaces.length); assertEquals(1, goatInterfaces.length);
assertEquals(1, animalInterfaces.length); assertEquals(1, animalInterfaces.length);
assertEquals("Locomotion", goatInterfaces[0].getSimpleName()); assertEquals("Locomotion", goatInterfaces[0].getSimpleName());
@ -94,6 +98,7 @@ public class ReflectionTest {
throws ClassNotFoundException { throws ClassNotFoundException {
Class<?> goatClass = Class.forName("com.baeldung.reflection.Goat"); Class<?> goatClass = Class.forName("com.baeldung.reflection.Goat");
Constructor<?>[] constructors = goatClass.getConstructors(); Constructor<?>[] constructors = goatClass.getConstructors();
assertEquals(1, constructors.length); assertEquals(1, constructors.length);
assertEquals("com.baeldung.reflection.Goat", constructors[0].getName()); assertEquals("com.baeldung.reflection.Goat", constructors[0].getName());
} }
@ -103,13 +108,11 @@ public class ReflectionTest {
throws ClassNotFoundException { throws ClassNotFoundException {
Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal"); Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal");
Field[] fields = animalClass.getDeclaredFields(); Field[] fields = animalClass.getDeclaredFields();
List<String> expectedFields = Arrays.asList(new String[] { "name",
"CATEGORY" }); List<String> actualFields = getFieldNames(fields);
List<String> actualFields = new ArrayList<>();
for (Field field : fields)
actualFields.add(field.getName());
assertEquals(2, actualFields.size()); assertEquals(2, actualFields.size());
assertTrue(actualFields.containsAll(expectedFields)); assertTrue(actualFields.containsAll(Arrays.asList("name", "CATEGORY")));
} }
@Test @Test
@ -117,14 +120,11 @@ public class ReflectionTest {
throws ClassNotFoundException { throws ClassNotFoundException {
Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal"); Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal");
Method[] methods = animalClass.getDeclaredMethods(); Method[] methods = animalClass.getDeclaredMethods();
List<String> expectedMethods = Arrays.asList(new String[] { "getName", List<String> actualMethods = getMethodNames(methods);
"setName", "getSound", "makeSound" });
List<String> actualMethods = new ArrayList<>();
for (Method method : methods)
actualMethods.add(method.getName());
assertEquals(4, actualMethods.size());
assertTrue(actualMethods.containsAll(expectedMethods));
assertEquals(4, actualMethods.size());
assertTrue(actualMethods.containsAll(Arrays.asList("getName",
"setName", "getSound", "makeSound")));
} }
@Test @Test
@ -132,13 +132,13 @@ public class ReflectionTest {
throws ClassNotFoundException { throws ClassNotFoundException {
Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird"); Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
Constructor<?>[] constructors = birdClass.getConstructors(); Constructor<?>[] constructors = birdClass.getConstructors();
assertEquals(3, constructors.length); assertEquals(3, constructors.length);
} }
@Test @Test
public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect() public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect()
throws ClassNotFoundException, NoSuchMethodException, throws Exception {
SecurityException {
Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird"); Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
Constructor<?> cons1 = birdClass.getConstructor(); Constructor<?> cons1 = birdClass.getConstructor();
Constructor<?> cons2 = birdClass.getConstructor(String.class); Constructor<?> cons2 = birdClass.getConstructor(String.class);
@ -148,17 +148,18 @@ public class ReflectionTest {
@Test @Test
public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect() public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect()
throws ClassNotFoundException, NoSuchMethodException, throws Exception {
SecurityException, InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird"); Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
Constructor<?> cons1 = birdClass.getConstructor(); Constructor<?> cons1 = birdClass.getConstructor();
Constructor<?> cons2 = birdClass.getConstructor(String.class); Constructor<?> cons2 = birdClass.getConstructor(String.class);
Constructor<?> cons3 = birdClass.getConstructor(String.class, Constructor<?> cons3 = birdClass.getConstructor(String.class,
boolean.class); boolean.class);
Bird bird1 = (Bird) cons1.newInstance(); Bird bird1 = (Bird) cons1.newInstance();
Bird bird2 = (Bird) cons2.newInstance("Weaver bird"); Bird bird2 = (Bird) cons2.newInstance("Weaver bird");
Bird bird3 = (Bird) cons3.newInstance("dove", true); Bird bird3 = (Bird) cons3.newInstance("dove", true);
assertEquals("bird", bird1.getName()); assertEquals("bird", bird1.getName());
assertEquals("Weaver bird", bird2.getName()); assertEquals("Weaver bird", bird2.getName());
assertEquals("dove", bird3.getName()); assertEquals("dove", bird3.getName());
@ -178,8 +179,7 @@ public class ReflectionTest {
@Test @Test
public void givenClass_whenGetsPublicFieldByName_thenCorrect() public void givenClass_whenGetsPublicFieldByName_thenCorrect()
throws ClassNotFoundException, NoSuchFieldException, throws Exception {
SecurityException {
Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird"); Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
Field field = birdClass.getField("CATEGORY"); Field field = birdClass.getField("CATEGORY");
assertEquals("CATEGORY", field.getName()); assertEquals("CATEGORY", field.getName());
@ -197,8 +197,7 @@ public class ReflectionTest {
@Test @Test
public void givenClass_whenGetsFieldsByName_thenCorrect() public void givenClass_whenGetsFieldsByName_thenCorrect()
throws ClassNotFoundException, NoSuchFieldException, throws Exception {
SecurityException {
Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird"); Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
Field field = birdClass.getDeclaredField("walks"); Field field = birdClass.getDeclaredField("walks");
assertEquals("walks", field.getName()); assertEquals("walks", field.getName());
@ -207,8 +206,7 @@ public class ReflectionTest {
@Test @Test
public void givenClassField_whenGetsType_thenCorrect() public void givenClassField_whenGetsType_thenCorrect()
throws ClassNotFoundException, NoSuchFieldException, throws Exception {
SecurityException {
Field field = Class.forName("com.baeldung.reflection.Bird") Field field = Class.forName("com.baeldung.reflection.Bird")
.getDeclaredField("walks"); .getDeclaredField("walks");
Class<?> fieldClass = field.getType(); Class<?> fieldClass = field.getType();
@ -217,8 +215,7 @@ public class ReflectionTest {
@Test @Test
public void givenClassField_whenSetsAndGetsValue_thenCorrect() public void givenClassField_whenSetsAndGetsValue_thenCorrect()
throws ClassNotFoundException, NoSuchFieldException, throws Exception {
SecurityException, InstantiationException, IllegalAccessException {
Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird"); Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
Bird bird = (Bird) birdClass.newInstance(); Bird bird = (Bird) birdClass.newInstance();
Field field = birdClass.getDeclaredField("walks"); Field field = birdClass.getDeclaredField("walks");
@ -236,8 +233,7 @@ public class ReflectionTest {
@Test @Test
public void givenClassField_whenGetsAndSetsWithNull_thenCorrect() public void givenClassField_whenGetsAndSetsWithNull_thenCorrect()
throws ClassNotFoundException, InstantiationException, throws Exception {
IllegalAccessException, NoSuchFieldException, SecurityException {
Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird"); Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
Field field = birdClass.getField("CATEGORY"); Field field = birdClass.getField("CATEGORY");
field.setAccessible(true); field.setAccessible(true);
@ -250,12 +246,11 @@ public class ReflectionTest {
throws ClassNotFoundException { throws ClassNotFoundException {
Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird"); Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
Method[] methods = birdClass.getMethods(); Method[] methods = birdClass.getMethods();
List<String> methodNames = new ArrayList<>(); List<String> methodNames = getMethodNames(methods);
for (Method method : methods)
methodNames.add(method.getName());
assertTrue(methodNames.containsAll(Arrays assertTrue(methodNames.containsAll(Arrays
.asList(new String[] { "equals", "notifyAll", "hashCode", .asList("equals", "notifyAll", "hashCode",
"walks", "eats", "toString" }))); "walks", "eats", "toString")));
} }
@ -263,12 +258,10 @@ public class ReflectionTest {
public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect() public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect()
throws ClassNotFoundException { throws ClassNotFoundException {
Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird"); Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
Method[] methods = birdClass.getDeclaredMethods(); List<String> actualMethodNames = getMethodNames(birdClass.getDeclaredMethods());
List<String> expectedMethodNames = Arrays.asList(new String[] {
"setWalks", "walks", "getSound", "eats" }); List<String> expectedMethodNames = Arrays.asList("setWalks", "walks", "getSound", "eats");
List<String> actualMethodNames = new ArrayList<>();
for (Method method : methods)
actualMethodNames.add(method.getName());
assertEquals(expectedMethodNames.size(), actualMethodNames.size()); assertEquals(expectedMethodNames.size(), actualMethodNames.size());
assertTrue(expectedMethodNames.containsAll(actualMethodNames)); assertTrue(expectedMethodNames.containsAll(actualMethodNames));
assertTrue(actualMethodNames.containsAll(expectedMethodNames)); assertTrue(actualMethodNames.containsAll(expectedMethodNames));
@ -277,16 +270,18 @@ public class ReflectionTest {
@Test @Test
public void givenMethodName_whenGetsMethod_thenCorrect() public void givenMethodName_whenGetsMethod_thenCorrect()
throws ClassNotFoundException, NoSuchMethodException, throws Exception {
SecurityException {
Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird"); Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
Method walksMethod = birdClass.getDeclaredMethod("walks"); Method walksMethod = birdClass.getDeclaredMethod("walks");
Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", Method setWalksMethod = birdClass.getDeclaredMethod("setWalks",
boolean.class); boolean.class);
assertFalse(walksMethod.isAccessible()); assertFalse(walksMethod.isAccessible());
assertFalse(setWalksMethod.isAccessible()); assertFalse(setWalksMethod.isAccessible());
walksMethod.setAccessible(true); walksMethod.setAccessible(true);
setWalksMethod.setAccessible(true); setWalksMethod.setAccessible(true);
assertTrue(walksMethod.isAccessible()); assertTrue(walksMethod.isAccessible());
assertTrue(setWalksMethod.isAccessible()); assertTrue(setWalksMethod.isAccessible());
@ -294,23 +289,35 @@ public class ReflectionTest {
@Test @Test
public void givenMethod_whenInvokes_thenCorrect() public void givenMethod_whenInvokes_thenCorrect()
throws ClassNotFoundException, NoSuchMethodException, throws Exception {
SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException,
InstantiationException {
Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird"); Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
Bird bird = (Bird) birdClass.newInstance(); Bird bird = (Bird) birdClass.newInstance();
Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", Method setWalksMethod = birdClass.getDeclaredMethod("setWalks",
boolean.class); boolean.class);
Method walksMethod = birdClass.getDeclaredMethod("walks"); Method walksMethod = birdClass.getDeclaredMethod("walks");
boolean walks = (boolean) walksMethod.invoke(bird); boolean walks = (boolean) walksMethod.invoke(bird);
assertFalse(walks); assertFalse(walks);
assertFalse(bird.walks()); assertFalse(bird.walks());
setWalksMethod.invoke(bird, true); setWalksMethod.invoke(bird, true);
boolean walks2 = (boolean) walksMethod.invoke(bird); boolean walks2 = (boolean) walksMethod.invoke(bird);
assertTrue(walks2); assertTrue(walks2);
assertTrue(bird.walks()); assertTrue(bird.walks());
} }
private static List<String> getMethodNames(Method[] methods) {
return Stream.of(methods)
.map((Method::getName))
.collect(toList());
}
private static List<String> getFieldNames(Field[] fields) {
return Stream.of(fields)
.map(Field::getName)
.collect(toList());
}
} }