From 962ed719acd6edd5113f3b1602d1cab6d53d332e Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Fri, 6 Jan 2023 04:29:23 +0100 Subject: [PATCH] [clsTypeByString] get class object from a string (#13233) --- .../baeldung/getclassfromstr/MyNiceClass.java | 7 ++++++ .../GetClassObjectFromStringUnitTest.java | 22 +++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 core-java-modules/core-java-reflection/src/main/java/com/baeldung/getclassfromstr/MyNiceClass.java create mode 100644 core-java-modules/core-java-reflection/src/test/java/com/baeldung/getclassfromstr/GetClassObjectFromStringUnitTest.java diff --git a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/getclassfromstr/MyNiceClass.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/getclassfromstr/MyNiceClass.java new file mode 100644 index 0000000000..c329421208 --- /dev/null +++ b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/getclassfromstr/MyNiceClass.java @@ -0,0 +1,7 @@ +package com.baeldung.getclassfromstr; + +public class MyNiceClass { + public String greeting(){ + return "Hi there, I wish you all the best!"; + } +} diff --git a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/getclassfromstr/GetClassObjectFromStringUnitTest.java b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/getclassfromstr/GetClassObjectFromStringUnitTest.java new file mode 100644 index 0000000000..f0e8022c02 --- /dev/null +++ b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/getclassfromstr/GetClassObjectFromStringUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.getclassfromstr; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class GetClassObjectFromStringUnitTest { + @Test + void givenQualifiedClsName_whenUsingClassForName_shouldGetExpectedClassObject() throws ReflectiveOperationException { + Class cls = Class.forName("com.baeldung.getclassfromstr.MyNiceClass"); + assertNotNull(cls); + + MyNiceClass myNiceObject = (MyNiceClass) cls.getDeclaredConstructor().newInstance(); + assertNotNull(myNiceObject); + assertEquals("Hi there, I wish you all the best!", myNiceObject.greeting()); + } + + @Test + void givenSimpleName_whenUsingClassForName_shouldGetExpectedException() { + assertThrows(ClassNotFoundException.class, () -> Class.forName("MyNiceClass")); + } +}