Merge pull request #10043 from sk1418/classObj

[BAEL-4532]a.getClass() vs A.class
This commit is contained in:
Eric Martin 2020-09-27 08:49:17 -05:00 committed by GitHub
commit dd2c527a69
6 changed files with 81 additions and 0 deletions

View File

@ -0,0 +1,5 @@
package com.baeldung.getclassobject;
public class Animal {
protected int numberOfEyes;
}

View File

@ -0,0 +1,4 @@
package com.baeldung.getclassobject;
public class Monkey extends Animal {
}

View File

@ -0,0 +1,4 @@
package com.baeldung.getclassobject;
public abstract class SomeAbstractClass {
}

View File

@ -0,0 +1,4 @@
package com.baeldung.getclassobject;
interface SomeInterface {
}

View File

@ -0,0 +1,9 @@
package com.baeldung.getclassobject;
public class SomeUtils {
private SomeUtils() {
throw new RuntimeException("This Util class is not allowed to be instantiated!");
}
// public static utilMethods
// ...
}

View File

@ -0,0 +1,55 @@
package com.baeldung.getclassobject;
import org.junit.Test;
import static org.junit.Assert.*;
public class GetClassObjectUnitTest {
@Test
public void givenObjectAndType_whenGettingClassObject_thenTwoMethodsHaveTheSameResult() {
String str = "I am an object of the String class";
Class fromStrObject = str.getClass();
Class clazz = String.class;
assertSame(fromStrObject, clazz);
}
@Test
public void givenClassInheritance_whenGettingRuntimeTypeAndStaticType_thenGetDifferentResult() {
Animal animal = new Monkey();
Class runtimeType = animal.getClass();
Class staticType = Animal.class;
//Not equals
assertNotEquals(staticType, runtimeType);
Class monkeyClass = Monkey.class;
assertSame(runtimeType, monkeyClass);
}
@Test
public void givenPrimitiveType_whenGettingClassObject_thenOnlyStaticTypeWorks() {
int number = 7;
// Class numberClass = number.getClass(); <-- compilation error
Class intType = int.class;
assertNotNull(intType);
assertEquals("int", intType.getName());
assertTrue(intType.isPrimitive());
}
@Test
public void givenTypeCannotInstantiate_whenGetTypeStatically_thenGetTypesSuccefully() {
Class interfaceType = SomeInterface.class;
Class abstractClassType = SomeAbstractClass.class;
Class utilClassType = SomeUtils.class;
assertNotNull(interfaceType);
assertTrue(interfaceType.isInterface());
assertEquals("SomeInterface", interfaceType.getSimpleName());
assertNotNull(abstractClassType);
assertEquals("SomeAbstractClass", abstractClassType.getSimpleName());
assertNotNull(utilClassType);
assertEquals("SomeUtils", utilClassType.getSimpleName());
}
}