[clsTypeByString] get class object from a string (#13233)

This commit is contained in:
Kai Yuan 2023-01-06 04:29:23 +01:00 committed by GitHub
parent 08dd5a6f90
commit 962ed719ac
2 changed files with 29 additions and 0 deletions

View File

@ -0,0 +1,7 @@
package com.baeldung.getclassfromstr;
public class MyNiceClass {
public String greeting(){
return "Hi there, I wish you all the best!";
}
}

View File

@ -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"));
}
}