diff --git a/core-java/src/main/java/com/baeldung/java/reflection/Animal.java b/core-java/src/main/java/com/baeldung/java/reflection/Animal.java index 2107c7522d..3f36243c29 100644 --- a/core-java/src/main/java/com/baeldung/java/reflection/Animal.java +++ b/core-java/src/main/java/com/baeldung/java/reflection/Animal.java @@ -18,10 +18,6 @@ public abstract class Animal implements Eating { this.name = name; } - public String makeSound() { - return getSound(); - } - protected abstract String getSound(); } diff --git a/core-java/src/test/java/com/baeldung/java/reflection/ReflectionTest.java b/core-java/src/test/java/com/baeldung/java/reflection/ReflectionTest.java index 6a0ad7d34f..a12a2f205f 100644 --- a/core-java/src/test/java/com/baeldung/java/reflection/ReflectionTest.java +++ b/core-java/src/test/java/com/baeldung/java/reflection/ReflectionTest.java @@ -8,9 +8,7 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.List; -import java.util.stream.Stream; - -import static java.util.stream.Collectors.toList; +import java.util.ArrayList; import static org.junit.Assert.*; public class ReflectionTest { @@ -24,7 +22,6 @@ public class ReflectionTest { assertTrue(Arrays.asList("name", "age") .containsAll(actualFieldNames)); - } @Test @@ -127,7 +124,7 @@ public class ReflectionTest { assertEquals(4, actualMethods.size()); assertTrue(actualMethods.containsAll(Arrays.asList("getName", - "setName", "getSound", "makeSound"))); + "setName", "getSound"))); } @Test @@ -311,16 +308,19 @@ public class ReflectionTest { } - private static List getMethodNames(Method[] methods) { - return Stream.of(methods) - .map((Method::getName)) - .collect(toList()); - } + private static List getFieldNames(Field[] fields) { + List fieldNames = new ArrayList<>(); + for (Field field : fields) + fieldNames.add(field.getName()); + return fieldNames; - private static List getFieldNames(Field[] fields) { - return Stream.of(fields) - .map(Field::getName) - .collect(toList()); - } + } + + private static List getMethodNames(Method[] methods) { + List methodNames = new ArrayList<>(); + for (Method method : methods) + methodNames.add(method.getName()); + return methodNames; + } } diff --git a/enterprise-patterns/front-controller-pattern/pom.xml b/enterprise-patterns/front-controller-pattern/pom.xml new file mode 100644 index 0000000000..dbcd4f1b1d --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + + front-controller-pattern + war + + + enterprise-patterns-parent + com.baeldung.enterprise.patterns + 1.0.0-SNAPSHOT + + + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + org.eclipse.jetty + jetty-maven-plugin + 9.4.0.M1 + + + /front-controller + + + + + + diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java new file mode 100644 index 0000000000..4dfc12c050 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java @@ -0,0 +1,45 @@ +package com.baeldung.enterprise.patterns.front.controller; + +import com.baeldung.enterprise.patterns.front.controller.commands.FrontCommand; +import com.baeldung.enterprise.patterns.front.controller.commands.UnknownCommand; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +public class FrontControllerServlet extends HttpServlet { + @Override + protected void doGet( + HttpServletRequest request, + HttpServletResponse response + ) throws ServletException, IOException { + FrontCommand command = getCommand(request); + command.init(getServletContext(), request, response); + command.process(); + } + + private FrontCommand getCommand(HttpServletRequest request) { + try { + return (FrontCommand) getCommandClass(request) + .asSubclass(FrontCommand.class) + .newInstance(); + } catch (Exception e) { + throw new RuntimeException("Failed to get command!", e); + } + } + + private Class getCommandClass(HttpServletRequest request) { + try { + return Class.forName( + String.format( + "com.baeldung.enterprise.patterns.front.controller.commands.%sCommand", + request.getParameter("command") + ) + ); + } catch (ClassNotFoundException e) { + return UnknownCommand.class; + } + } +} diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java new file mode 100644 index 0000000000..12a008faeb --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java @@ -0,0 +1,32 @@ +package com.baeldung.enterprise.patterns.front.controller.commands; + +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +public abstract class FrontCommand { + protected ServletContext context; + protected HttpServletRequest request; + protected HttpServletResponse response; + + public void init( + ServletContext servletContext, + HttpServletRequest servletRequest, + HttpServletResponse servletResponse + ) { + this.context = servletContext; + this.request = servletRequest; + this.response = servletResponse; + } + + public abstract void process() throws ServletException, IOException; + + protected void forward(String target) throws ServletException, IOException { + target = String.format("/WEB-INF/jsp/%s.jsp", target); + RequestDispatcher dispatcher = context.getRequestDispatcher(target); + dispatcher.forward(request, response); + } +} diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java new file mode 100644 index 0000000000..0c5bd64bbc --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java @@ -0,0 +1,21 @@ +package com.baeldung.enterprise.patterns.front.controller.commands; + +import com.baeldung.enterprise.patterns.front.controller.data.Book; +import com.baeldung.enterprise.patterns.front.controller.data.BookshelfImpl; + +import javax.servlet.ServletException; +import java.io.IOException; + +public class SearchCommand extends FrontCommand { + @Override + public void process() throws ServletException, IOException { + Book book = new BookshelfImpl().getInstance() + .findByTitle(request.getParameter("title")); + if (book != null) { + request.setAttribute("book", book); + forward("book-found"); + } else { + forward("book-notfound"); + } + } +} diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java new file mode 100644 index 0000000000..90103c8f42 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java @@ -0,0 +1,11 @@ +package com.baeldung.enterprise.patterns.front.controller.commands; + +import javax.servlet.ServletException; +import java.io.IOException; + +public class UnknownCommand extends FrontCommand { + @Override + public void process() throws ServletException, IOException { + forward("unknown"); + } +} diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java new file mode 100644 index 0000000000..634e05c3a0 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java @@ -0,0 +1,40 @@ +package com.baeldung.enterprise.patterns.front.controller.data; + +public class Book { + private String author; + private String title; + private Double price; + + public Book() { + } + + public Book(String author, String title, Double price) { + this.author = author; + this.title = title; + this.price = price; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Double getPrice() { + return price; + } + + public void setPrice(Double price) { + this.price = price; + } +} diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java new file mode 100644 index 0000000000..524e000bd9 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java @@ -0,0 +1,15 @@ +package com.baeldung.enterprise.patterns.front.controller.data; + +public interface Bookshelf { + + default void init() { + add(new Book("Wilson, Robert Anton & Shea, Robert", "Illuminati", 9.99)); + add(new Book("Fowler, Martin", "Patterns of Enterprise Application Architecture", 27.88)); + } + + Bookshelf getInstance(); + + boolean add(E book); + + Book findByTitle(String title); +} diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java new file mode 100644 index 0000000000..3862418857 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java @@ -0,0 +1,24 @@ +package com.baeldung.enterprise.patterns.front.controller.data; + +import java.util.ArrayList; + +public class BookshelfImpl extends ArrayList implements Bookshelf { + private static Bookshelf INSTANCE; + + @Override + public Bookshelf getInstance() { + if (INSTANCE == null) { + INSTANCE = new BookshelfImpl(); + INSTANCE.init(); + } + return INSTANCE; + } + + @Override + public Book findByTitle(String title) { + return this.stream() + .filter(book -> book.getTitle().toLowerCase().contains(title.toLowerCase())) + .findFirst() + .orElse(null); + } +} diff --git a/enterprise-patterns/front-controller-pattern/src/main/resources/front controller.png b/enterprise-patterns/front-controller-pattern/src/main/resources/front controller.png new file mode 100644 index 0000000000..bd475bf3f3 Binary files /dev/null and b/enterprise-patterns/front-controller-pattern/src/main/resources/front controller.png differ diff --git a/enterprise-patterns/front-controller-pattern/src/main/resources/front controller.puml b/enterprise-patterns/front-controller-pattern/src/main/resources/front controller.puml new file mode 100644 index 0000000000..fbd4f416ef --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/resources/front controller.puml @@ -0,0 +1,22 @@ +@startuml + +class Handler { +doGet +doPost +} + +abstract class AbstractCommand { +process +} +class ConcreteCommand1 { +process +} +class ConcreteCommand2 { +process +} + +Handler .right.> AbstractCommand +AbstractCommand <|-- ConcreteCommand1 +AbstractCommand <|-- ConcreteCommand2 + +@enduml \ No newline at end of file diff --git a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-found.jsp b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-found.jsp new file mode 100644 index 0000000000..42e08b4a46 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-found.jsp @@ -0,0 +1,12 @@ + + + + Bookshelf: Title found + + +

Our Bookshelf contains this title:

+

${book.getTitle()}

+

Author: ${book.getAuthor()}

+ + + diff --git a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-notfound.jsp b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-notfound.jsp new file mode 100644 index 0000000000..2f8ac01755 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-notfound.jsp @@ -0,0 +1,10 @@ + + + + Bookshelf: Title not found + + +

Our Bookshelf doesn't contains this title:

+

${param.get("title")}

+ + diff --git a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/unknown.jsp b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/unknown.jsp new file mode 100644 index 0000000000..b52b2de8d5 --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/unknown.jsp @@ -0,0 +1,9 @@ + + + + Bookshelf: Command unknown + + +

Sorry, this command is not known!

+ + diff --git a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/web.xml b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..77113db09b --- /dev/null +++ b/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + front-controller + com.baeldung.enterprise.patterns.front.controller.FrontControllerServlet + + + front-controller + / + + diff --git a/enterprise-patterns/pom.xml b/enterprise-patterns/pom.xml new file mode 100644 index 0000000000..2fba12547f --- /dev/null +++ b/enterprise-patterns/pom.xml @@ -0,0 +1,35 @@ + + + 4.0.0 + + com.baeldung.enterprise.patterns + enterprise-patterns-parent + pom + + front-controller-pattern + + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + + diff --git a/pom.xml b/pom.xml index 6395fcd49b..db3fa8a21c 100644 --- a/pom.xml +++ b/pom.xml @@ -29,6 +29,8 @@ dozer dependency-injection deltaspike + + enterprise-patterns gson diff --git a/reflection/pom.xml b/reflection/pom.xml deleted file mode 100644 index 10a6d7df0c..0000000000 --- a/reflection/pom.xml +++ /dev/null @@ -1,30 +0,0 @@ - - 4.0.0 - com.baeldung - reflection - 1.0 - reflection - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.3 - - 8 - 8 - - - - - - - junit - junit - 4.3 - test - - - - diff --git a/reflection/src/main/java/com/baeldung/reflection/Animal.java b/reflection/src/main/java/com/baeldung/reflection/Animal.java deleted file mode 100644 index 364246ae64..0000000000 --- a/reflection/src/main/java/com/baeldung/reflection/Animal.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.reflection; - -public abstract class Animal implements Eating { - - public static final String CATEGORY = "domestic"; - - private String name; - - public Animal(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - protected abstract String getSound(); - -} diff --git a/reflection/src/main/java/com/baeldung/reflection/Bird.java b/reflection/src/main/java/com/baeldung/reflection/Bird.java deleted file mode 100644 index f5bb0f9b19..0000000000 --- a/reflection/src/main/java/com/baeldung/reflection/Bird.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.reflection; - -public class Bird extends Animal { - private boolean walks; - - public Bird() { - super("bird"); - } - - public Bird(String name, boolean walks) { - super(name); - setWalks(walks); - } - - public Bird(String name) { - super(name); - } - - @Override - public String eats() { - return "grains"; - } - - @Override - protected String getSound() { - return "chaps"; - } - - public boolean walks() { - return walks; - } - - public void setWalks(boolean walks) { - this.walks = walks; - } -} diff --git a/reflection/src/main/java/com/baeldung/reflection/Eating.java b/reflection/src/main/java/com/baeldung/reflection/Eating.java deleted file mode 100644 index c959becf00..0000000000 --- a/reflection/src/main/java/com/baeldung/reflection/Eating.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.baeldung.reflection; - -public interface Eating { - String eats(); -} diff --git a/reflection/src/main/java/com/baeldung/reflection/Goat.java b/reflection/src/main/java/com/baeldung/reflection/Goat.java deleted file mode 100644 index 086d09d543..0000000000 --- a/reflection/src/main/java/com/baeldung/reflection/Goat.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.reflection; - -public class Goat extends Animal implements Locomotion { - - public Goat(String name) { - super(name); - } - - @Override - protected String getSound() { - return "bleat"; - } - - @Override - public String getLocomotion() { - return "walks"; - } - - @Override - public String eats() { - return "grass"; - } - -} diff --git a/reflection/src/main/java/com/baeldung/reflection/Locomotion.java b/reflection/src/main/java/com/baeldung/reflection/Locomotion.java deleted file mode 100644 index 230fd9a466..0000000000 --- a/reflection/src/main/java/com/baeldung/reflection/Locomotion.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.baeldung.reflection; - -public interface Locomotion { - String getLocomotion(); -} diff --git a/reflection/src/main/java/com/baeldung/reflection/Person.java b/reflection/src/main/java/com/baeldung/reflection/Person.java deleted file mode 100644 index 1a1fafef93..0000000000 --- a/reflection/src/main/java/com/baeldung/reflection/Person.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.baeldung.reflection; - -public class Person { - private String name; - private int age; -} diff --git a/reflection/src/test/java/com/baeldung/reflection/ReflectionTest.java b/reflection/src/test/java/com/baeldung/reflection/ReflectionTest.java deleted file mode 100644 index 180ea38098..0000000000 --- a/reflection/src/test/java/com/baeldung/reflection/ReflectionTest.java +++ /dev/null @@ -1,323 +0,0 @@ -package com.baeldung.reflection; - -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 { - - @Test - public void givenObject_whenGetsFieldNamesAtRuntime_thenCorrect() { - Object person = new Person(); - Field[] fields = person.getClass().getDeclaredFields(); - - List actualFieldNames = getFieldNames(fields); - - assertTrue(Arrays.asList("name", "age") - .containsAll(actualFieldNames)); - - } - - @Test - public void givenObject_whenGetsClassName_thenCorrect() { - Object goat = new Goat("goat"); - Class clazz = goat.getClass(); - - assertEquals("Goat", clazz.getSimpleName()); - assertEquals("com.baeldung.reflection.Goat", clazz.getName()); - assertEquals("com.baeldung.reflection.Goat", clazz.getCanonicalName()); - } - - @Test - public void givenClassName_whenCreatesObject_thenCorrect() - throws ClassNotFoundException { - Class clazz = Class.forName("com.baeldung.reflection.Goat"); - - assertEquals("Goat", clazz.getSimpleName()); - assertEquals("com.baeldung.reflection.Goat", clazz.getName()); - assertEquals("com.baeldung.reflection.Goat", clazz.getCanonicalName()); - } - - @Test - public void givenClass_whenRecognisesModifiers_thenCorrect() - throws ClassNotFoundException { - Class goatClass = Class.forName("com.baeldung.reflection.Goat"); - Class animalClass = Class.forName("com.baeldung.reflection.Animal"); - int goatMods = goatClass.getModifiers(); - int animalMods = animalClass.getModifiers(); - - assertTrue(Modifier.isPublic(goatMods)); - assertTrue(Modifier.isAbstract(animalMods)); - assertTrue(Modifier.isPublic(animalMods)); - } - - @Test - public void givenClass_whenGetsPackageInfo_thenCorrect() { - Goat goat = new Goat("goat"); - Class goatClass = goat.getClass(); - Package pkg = goatClass.getPackage(); - - assertEquals("com.baeldung.reflection", pkg.getName()); - } - - @Test - public void givenClass_whenGetsSuperClass_thenCorrect() { - Goat goat = new Goat("goat"); - String str = "any string"; - - Class goatClass = goat.getClass(); - Class goatSuperClass = goatClass.getSuperclass(); - - assertEquals("Animal", goatSuperClass.getSimpleName()); - assertEquals("Object", str.getClass().getSuperclass().getSimpleName()); - - } - - @Test - public void givenClass_whenGetsImplementedInterfaces_thenCorrect() - throws ClassNotFoundException { - Class goatClass = Class.forName("com.baeldung.reflection.Goat"); - Class animalClass = Class.forName("com.baeldung.reflection.Animal"); - Class[] goatInterfaces = goatClass.getInterfaces(); - Class[] animalInterfaces = animalClass.getInterfaces(); - - assertEquals(1, goatInterfaces.length); - assertEquals(1, animalInterfaces.length); - assertEquals("Locomotion", goatInterfaces[0].getSimpleName()); - assertEquals("Eating", animalInterfaces[0].getSimpleName()); - } - - @Test - public void givenClass_whenGetsConstructor_thenCorrect() - throws ClassNotFoundException { - Class goatClass = Class.forName("com.baeldung.reflection.Goat"); - Constructor[] constructors = goatClass.getConstructors(); - - assertEquals(1, constructors.length); - assertEquals("com.baeldung.reflection.Goat", constructors[0].getName()); - } - - @Test - public void givenClass_whenGetsFields_thenCorrect() - throws ClassNotFoundException { - Class animalClass = Class.forName("com.baeldung.reflection.Animal"); - Field[] fields = animalClass.getDeclaredFields(); - - List actualFields = getFieldNames(fields); - - assertEquals(2, actualFields.size()); - assertTrue(actualFields.containsAll(Arrays.asList("name", "CATEGORY"))); - } - - @Test - public void givenClass_whenGetsMethods_thenCorrect() - throws ClassNotFoundException { - Class animalClass = Class.forName("com.baeldung.reflection.Animal"); - Method[] methods = animalClass.getDeclaredMethods(); - List actualMethods = getMethodNames(methods); - - assertEquals(4, actualMethods.size()); - assertTrue(actualMethods.containsAll(Arrays.asList("getName", - "setName", "getSound", "makeSound"))); - } - - @Test - public void givenClass_whenGetsAllConstructors_thenCorrect() - throws ClassNotFoundException { - Class birdClass = Class.forName("com.baeldung.reflection.Bird"); - Constructor[] constructors = birdClass.getConstructors(); - - assertEquals(3, constructors.length); - } - - @Test - public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect() - throws Exception { - Class birdClass = Class.forName("com.baeldung.reflection.Bird"); - Constructor cons1 = birdClass.getConstructor(); - Constructor cons2 = birdClass.getConstructor(String.class); - Constructor cons3 = birdClass.getConstructor(String.class, - boolean.class); - } - - @Test - public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect() - throws Exception { - Class birdClass = Class.forName("com.baeldung.reflection.Bird"); - - Constructor cons1 = birdClass.getConstructor(); - Constructor cons2 = birdClass.getConstructor(String.class); - Constructor cons3 = birdClass.getConstructor(String.class, - boolean.class); - - Bird bird1 = (Bird) cons1.newInstance(); - Bird bird2 = (Bird) cons2.newInstance("Weaver bird"); - Bird bird3 = (Bird) cons3.newInstance("dove", true); - - assertEquals("bird", bird1.getName()); - assertEquals("Weaver bird", bird2.getName()); - assertEquals("dove", bird3.getName()); - assertFalse(bird1.walks()); - assertTrue(bird3.walks()); - } - - @Test - public void givenClass_whenGetsPublicFields_thenCorrect() - throws ClassNotFoundException { - Class birdClass = Class.forName("com.baeldung.reflection.Bird"); - Field[] fields = birdClass.getFields(); - assertEquals(1, fields.length); - assertEquals("CATEGORY", fields[0].getName()); - - } - - @Test - public void givenClass_whenGetsPublicFieldByName_thenCorrect() - throws Exception { - Class birdClass = Class.forName("com.baeldung.reflection.Bird"); - Field field = birdClass.getField("CATEGORY"); - assertEquals("CATEGORY", field.getName()); - - } - - @Test - public void givenClass_whenGetsDeclaredFields_thenCorrect() - throws ClassNotFoundException { - Class birdClass = Class.forName("com.baeldung.reflection.Bird"); - Field[] fields = birdClass.getDeclaredFields(); - assertEquals(1, fields.length); - assertEquals("walks", fields[0].getName()); - } - - @Test - public void givenClass_whenGetsFieldsByName_thenCorrect() - throws Exception { - Class birdClass = Class.forName("com.baeldung.reflection.Bird"); - Field field = birdClass.getDeclaredField("walks"); - assertEquals("walks", field.getName()); - - } - - @Test - public void givenClassField_whenGetsType_thenCorrect() - throws Exception { - Field field = Class.forName("com.baeldung.reflection.Bird") - .getDeclaredField("walks"); - Class fieldClass = field.getType(); - assertEquals("boolean", fieldClass.getSimpleName()); - } - - @Test - public void givenClassField_whenSetsAndGetsValue_thenCorrect() - throws Exception { - Class birdClass = Class.forName("com.baeldung.reflection.Bird"); - Bird bird = (Bird) birdClass.newInstance(); - Field field = birdClass.getDeclaredField("walks"); - field.setAccessible(true); - - assertFalse(field.getBoolean(bird)); - assertFalse(bird.walks()); - - field.set(bird, true); - - assertTrue(field.getBoolean(bird)); - assertTrue(bird.walks()); - - } - - @Test - public void givenClassField_whenGetsAndSetsWithNull_thenCorrect() - throws Exception { - Class birdClass = Class.forName("com.baeldung.reflection.Bird"); - Field field = birdClass.getField("CATEGORY"); - field.setAccessible(true); - - assertEquals("domestic", field.get(null)); - } - - @Test - public void givenClass_whenGetsAllPublicMethods_thenCorrect() - throws ClassNotFoundException { - Class birdClass = Class.forName("com.baeldung.reflection.Bird"); - Method[] methods = birdClass.getMethods(); - List methodNames = getMethodNames(methods); - - assertTrue(methodNames.containsAll(Arrays - .asList("equals", "notifyAll", "hashCode", - "walks", "eats", "toString"))); - - } - - @Test - public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect() - throws ClassNotFoundException { - Class birdClass = Class.forName("com.baeldung.reflection.Bird"); - List actualMethodNames = getMethodNames(birdClass.getDeclaredMethods()); - - List expectedMethodNames = Arrays.asList("setWalks", "walks", "getSound", "eats"); - - assertEquals(expectedMethodNames.size(), actualMethodNames.size()); - assertTrue(expectedMethodNames.containsAll(actualMethodNames)); - assertTrue(actualMethodNames.containsAll(expectedMethodNames)); - - } - - @Test - public void givenMethodName_whenGetsMethod_thenCorrect() - throws Exception { - Class birdClass = Class.forName("com.baeldung.reflection.Bird"); - Method walksMethod = birdClass.getDeclaredMethod("walks"); - Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", - boolean.class); - - assertFalse(walksMethod.isAccessible()); - assertFalse(setWalksMethod.isAccessible()); - - walksMethod.setAccessible(true); - setWalksMethod.setAccessible(true); - - assertTrue(walksMethod.isAccessible()); - assertTrue(setWalksMethod.isAccessible()); - - } - - @Test - public void givenMethod_whenInvokes_thenCorrect() - throws Exception { - Class birdClass = Class.forName("com.baeldung.reflection.Bird"); - Bird bird = (Bird) birdClass.newInstance(); - Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", - boolean.class); - Method walksMethod = birdClass.getDeclaredMethod("walks"); - boolean walks = (boolean) walksMethod.invoke(bird); - - assertFalse(walks); - assertFalse(bird.walks()); - - setWalksMethod.invoke(bird, true); - boolean walks2 = (boolean) walksMethod.invoke(bird); - - assertTrue(walks2); - assertTrue(bird.walks()); - - } - - private static List getMethodNames(Method[] methods) { - return Stream.of(methods) - .map((Method::getName)) - .collect(toList()); - } - - private static List getFieldNames(Field[] fields) { - return Stream.of(fields) - .map(Field::getName) - .collect(toList()); - } - -}