Merge branch 'master' of https://github.com/vikasrajput6035/tutorials into BAEL-4936

This commit is contained in:
Vikas Ramsingh Rajput
2021-05-16 09:34:51 +05:30
6089 changed files with 116312 additions and 47802 deletions
+4 -1
View File
@@ -5,7 +5,10 @@ This module contains articles about Java 10 core features
### Relevant Articles:
- [Java 10 LocalVariable Type-Inference](http://www.baeldung.com/java-10-local-variable-type-inference)
- [Guide to Java 10](http://www.baeldung.com/java-10-overview)
- [New Features in Java 10](https://www.baeldung.com/java-10-overview)
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
- [Deep Dive Into the New Java JIT Compiler – Graal](https://www.baeldung.com/graal-java-jit-compiler)
- [Copying Sets in Java](https://www.baeldung.com/java-copy-sets)
- [Converting between a List and a Set in Java](https://www.baeldung.com/convert-list-to-set-and-set-to-list)
- [Java IndexOutOfBoundsException “Source Does Not Fit in Dest”](https://www.baeldung.com/java-indexoutofboundsexception)
- [Collect a Java Stream to an Immutable Collection](https://www.baeldung.com/java-stream-immutable-collection)
+16 -8
View File
@@ -1,22 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-10</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-10</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
@@ -34,6 +41,7 @@
<properties>
<maven.compiler.source.version>10</maven.compiler.source.version>
<maven.compiler.target.version>10</maven.compiler.target.version>
<commons-collections4.version>4.1</commons-collections4.version>
</properties>
</project>
@@ -7,7 +7,7 @@ import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
public class AppUnitTest
extends TestCase
{
/**
@@ -15,7 +15,7 @@ public class AppTest
*
* @param testName name of the test case
*/
public AppTest( String testName )
public AppUnitTest(String testName )
{
super( testName );
}
@@ -25,7 +25,7 @@ public class AppTest
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
return new TestSuite( AppUnitTest.class );
}
/**
@@ -0,0 +1,68 @@
package com.baeldung.java10.collections.conversion;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ListSetConversionUnitTest {
// Set -> List; List -> Set
@Test
public final void givenUsingCoreJava_whenSetConvertedToList_thenCorrect() {
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
final List<Integer> targetList = new ArrayList<>(sourceSet);
}
@Test
public final void givenUsingCoreJava_whenListConvertedToSet_thenCorrect() {
final List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
final Set<Integer> targetSet = new HashSet<>(sourceList);
}
@Test
public void givenUsingJava10_whenSetConvertedToList_thenCorrect() {
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
final List<Integer> targetList = List.copyOf(sourceSet);
}
@Test
public void givenUsingJava10_whenListConvertedToSet_thenCorrect() {
final List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
final Set<Integer> targetSet = Set.copyOf(sourceList);
}
@Test
public final void givenUsingGuava_whenSetConvertedToList_thenCorrect() {
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
final List<Integer> targetList = Lists.newArrayList(sourceSet);
}
@Test
public final void givenUsingGuava_whenListConvertedToSet_thenCorrect() {
final List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
final Set<Integer> targetSet = Sets.newHashSet(sourceList);
}
@Test
public final void givenUsingCommonsCollections_whenListConvertedToSet_thenCorrect() {
final List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
final Set<Integer> targetSet = new HashSet<>(6);
CollectionUtils.addAll(targetSet, sourceList);
}
@Test
public final void givenUsingCommonsCollections_whenSetConvertedToList_thenCorrect() {
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
final List<Integer> targetList = new ArrayList<>(6);
CollectionUtils.addAll(targetList, sourceSet);
}
}
@@ -10,5 +10,6 @@ public class CopyListServiceUnitTest {
@Test(expected = UnsupportedOperationException.class)
public void whenModifyCopyOfList_thenThrowsException() {
List<Integer> copyList = List.copyOf(Arrays.asList(1, 2, 3, 4));
copyList.add(4);
}
}
@@ -0,0 +1,20 @@
package com.baeldung.java10.streams;
import static java.util.stream.Collectors.toUnmodifiableList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
public class StreamToImmutableJava10UnitTest {
@Test
public void whenUsingCollectorsToUnmodifiableList_thenSuccess() {
List<String> givenList = Arrays.asList("a", "b", "c");
List<String> result = givenList.stream()
.collect(toUnmodifiableList());
System.out.println(result.getClass());
}
}
@@ -0,0 +1,9 @@
## Core Java 11
This module contains articles about Java 11 core features
### Relevant articles
- [Guide to Java 8 Optional](https://www.baeldung.com/java-optional)
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
- [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors)
- [New Features in Java 11](https://www.baeldung.com/java-11-new-features)
+79
View File
@@ -0,0 +1,79 @@
<?xml version="1.0" encoding="UTF-8"?>
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-11-2</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-11-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../..</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-junit-jupiter</artifactId>
<version>${mockserver.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source.version}</source>
<target>${maven.compiler.target.version}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source.version>11</maven.compiler.source.version>
<maven.compiler.target.version>11</maven.compiler.target.version>
<guava.version>29.0-jre</guava.version>
<junit.jupiter.version>5.7.0</junit.jupiter.version>
<assertj.version>3.17.2</assertj.version>
<mockserver.version>5.11.1</mockserver.version>
</properties>
</project>
@@ -0,0 +1,17 @@
package com.baeldung.features;
public class MainClass {
private static boolean mainPrivateMethod() {
return true;
}
public static class NestedClass {
boolean nestedPublicMethod() {
return mainPrivateMethod();
}
}
}
@@ -1,4 +1,4 @@
package com.baeldung.java.reflection;
package com.baeldung.reflection;
public abstract class Animal implements Eating {
@@ -1,4 +1,4 @@
package com.baeldung.java.reflection;
package com.baeldung.reflection;
public class Bird extends Animal {
private boolean walks;
@@ -1,4 +1,4 @@
package com.baeldung.java.reflection;
package com.baeldung.reflection;
import java.lang.annotation.Annotation;
@@ -1,4 +1,4 @@
package com.baeldung.java.reflection;
package com.baeldung.reflection;
public interface Eating {
String eats();
@@ -1,4 +1,4 @@
package com.baeldung.java.reflection;
package com.baeldung.reflection;
public class Goat extends Animal implements Locomotion {
@@ -1,4 +1,4 @@
package com.baeldung.java.reflection;
package com.baeldung.reflection;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -1,4 +1,4 @@
package com.baeldung.java.reflection;
package com.baeldung.reflection;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
@@ -1,4 +1,4 @@
package com.baeldung.java.reflection;
package com.baeldung.reflection;
@Greeter(greet="Good morning")
public class Greetings {
@@ -1,4 +1,4 @@
package com.baeldung.java.reflection;
package com.baeldung.reflection;
public interface Locomotion {
String getLocomotion();
@@ -1,4 +1,4 @@
package com.baeldung.java.reflection;
package com.baeldung.reflection;
public class Operations {
@@ -1,4 +1,4 @@
package com.baeldung.java.reflection;
package com.baeldung.reflection;
public class Person {
private String name;
@@ -1,18 +1,11 @@
package com.baeldung.streams.collectors;
package com.baeldung.collectors;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import org.junit.Test;
import java.util.Arrays;
import java.util.Comparator;
import java.util.DoubleSummaryStatistics;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
@@ -20,19 +13,7 @@ import java.util.function.Supplier;
import java.util.stream.Collector;
import static com.google.common.collect.Sets.newHashSet;
import static java.util.stream.Collectors.averagingDouble;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.maxBy;
import static java.util.stream.Collectors.partitioningBy;
import static java.util.stream.Collectors.summarizingDouble;
import static java.util.stream.Collectors.summingDouble;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.Collectors.toSet;
import static java.util.stream.Collectors.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@@ -48,6 +29,14 @@ public class Java8CollectorsUnitTest {
assertThat(result).containsAll(givenList);
}
@Test
public void whenCollectingToUnmodifiableList_shouldCollectToUnmodifiableList() {
final List<String> result = givenList.stream().collect(toUnmodifiableList());
assertThatThrownBy(() -> result.add("foo"))
.isInstanceOf(UnsupportedOperationException.class);
}
@Test
public void whenCollectingToSet_shouldCollectToSet() throws Exception {
final Set<String> result = givenList.stream().collect(toSet());
@@ -55,6 +44,14 @@ public class Java8CollectorsUnitTest {
assertThat(result).containsAll(givenList);
}
@Test
public void whenCollectingToUnmodifiableSet_shouldCollectToUnmodifiableSet() {
final Set<String> result = givenList.stream().collect(toUnmodifiableSet());
assertThatThrownBy(() -> result.add("foo"))
.isInstanceOf(UnsupportedOperationException.class);
}
@Test
public void givenContainsDuplicateElements_whenCollectingToSet_shouldAddDuplicateElementsOnlyOnce() throws Exception {
final Set<String> result = listWithDuplicates.stream().collect(toSet());
@@ -84,6 +81,15 @@ public class Java8CollectorsUnitTest {
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
}
@Test
public void whenCollectingToUnmodifiableMap_shouldCollectToUnmodifiableMap() {
final Map<String, Integer> result = givenList.stream()
.collect(toUnmodifiableMap(Function.identity(), String::length));
assertThatThrownBy(() -> result.put("foo", 3))
.isInstanceOf(UnsupportedOperationException.class);
}
@Test
public void whenCollectingToMapwWithDuplicates_shouldCollectToMapMergingTheIdenticalItems() throws Exception {
final Map<String, Integer> result = listWithDuplicates.stream().collect(
@@ -0,0 +1,54 @@
package com.baeldung.features;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockserver.integration.ClientAndServer;
import org.mockserver.model.HttpStatusCode;
import org.mockserver.socket.PortFactory;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
class HttpClientIntegrationTest {
private static ClientAndServer mockServer;
private static int port;
@BeforeAll
static void startServer() {
port = PortFactory.findFreePort();
mockServer = startClientAndServer(port);
mockServer.when(new org.mockserver.model.HttpRequest().withMethod("GET"))
.respond(new org.mockserver.model.HttpResponse()
.withStatusCode(HttpStatusCode.OK_200.code())
.withBody("Hello from the server!"));
}
@AfterAll
static void stopServer() {
mockServer.stop();
}
@Test
void givenSampleHttpRequest_whenRequestIsSent_thenServerResponseIsReceived() throws IOException, InterruptedException {
HttpClient httpClient = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(20))
.build();
HttpRequest httpRequest = HttpRequest.newBuilder()
.GET()
.uri(URI.create("http://localhost:" + port))
.build();
HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
assertThat(httpResponse.body()).isEqualTo("Hello from the server!");
}
}
@@ -0,0 +1,61 @@
package com.baeldung.features;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
class JavaElevenFeaturesUnitTest {
@Test
void givenMultilineString_whenExtractingNonBlankStrippedLines_thenLinesAreReturned() {
String multilineString = "Baeldung helps \n \n developers \n explore Java.";
List<String> lines = multilineString.lines()
.filter(line -> !line.isBlank())
.map(String::strip)
.collect(Collectors.toList());
assertThat(lines).containsExactly("Baeldung helps", "developers", "explore Java.");
}
@Test
void givenTemporaryFile_whenReadingStringContent_thenContentIsReturned(@TempDir Path tempDir) throws IOException {
Path filePath = Files.writeString(Files.createTempFile(tempDir, "demo", ".txt"), "Sample text");
String fileContent = Files.readString(filePath);
assertThat(fileContent).isEqualTo("Sample text");
}
@Test
void givenSampleList_whenConvertingToArray_thenItemsRemainUnchanged() {
List<String> sampleList = Arrays.asList("Java", "Kotlin");
String[] sampleArray = sampleList.toArray(String[]::new);
assertThat(sampleArray).containsExactly("Java", "Kotlin");
}
@Test
void givenSampleList_whenConvertingToUppercaseString_thenUppercaseIsReturned() {
List<String> sampleList = Arrays.asList("Java", "Kotlin");
String resultString = sampleList.stream()
.map((@Nonnull var x) -> x.toUpperCase())
.collect(Collectors.joining(", "));
assertThat(resultString).isEqualTo("JAVA, KOTLIN");
}
@Test
void givenSampleList_whenExtractingNonBlankValues_thenOnlyNonBlanksAreReturned() {
List<String> sampleList = Arrays.asList("Java", "\n \n", "Kotlin", " ");
List<String> withoutBlanks = sampleList.stream()
.filter(Predicate.not(String::isBlank))
.collect(Collectors.toList());
assertThat(withoutBlanks).containsExactly("Java", "Kotlin");
}
}
@@ -0,0 +1,37 @@
package com.baeldung.features;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
class NestedClassesUnitTest {
@Test
public void giveNestedClass_whenCallingMainClassPrivateMethod_thenNoExceptionIsThrown() {
MainClass.NestedClass nestedInstance = new MainClass.NestedClass();
assertThat(nestedInstance.nestedPublicMethod()).isTrue();
}
@Test
public void giveNestedClass_whenCheckingNestmate_thenNestedClassIsReturned() {
assertThat(MainClass.class.isNestmateOf(MainClass.NestedClass.class)).isTrue();
}
@Test
public void giveNestedClass_whenCheckingNestHost_thenMainClassIsReturned() {
assertThat(MainClass.NestedClass.class.getNestHost()).isEqualTo(MainClass.class);
}
@Test
public void giveNestedClass_whenCheckingNestMembers_thenNestMembersAreReturned() {
Set<String> nestedMembers = Arrays.stream(MainClass.NestedClass.class.getNestMembers())
.map(Class::getName)
.collect(Collectors.toSet());
assertThat(nestedMembers).contains(MainClass.class.getName(), MainClass.NestedClass.class.getName());
}
}
@@ -7,7 +7,9 @@ import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class OptionalChainingUnitTest {
@@ -9,7 +9,9 @@ import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class OptionalUnitTest {
@@ -262,6 +264,12 @@ public class OptionalUnitTest {
.orElseThrow(IllegalArgumentException::new);
}
@Test(expected = NoSuchElementException.class)
public void whenNoArgOrElseThrowWorks_thenCorrect() {
String nullName = null;
String name = Optional.ofNullable(nullName).orElseThrow();
}
public String getMyDefault() {
LOG.debug("Getting default value...");
return "Default Value";
@@ -1,4 +1,4 @@
package com.baeldung.java.reflection;
package com.baeldung.reflection;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertFalse;
@@ -1,4 +1,4 @@
package com.baeldung.java.reflection;
package com.baeldung.reflection;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -32,23 +32,23 @@ public class ReflectionUnitTest {
final Class<?> clazz = goat.getClass();
assertEquals("Goat", clazz.getSimpleName());
assertEquals("com.baeldung.java.reflection.Goat", clazz.getName());
assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName());
assertEquals("com.baeldung.reflection.Goat", clazz.getName());
assertEquals("com.baeldung.reflection.Goat", clazz.getCanonicalName());
}
@Test
public void givenClassName_whenCreatesObject_thenCorrect() throws ClassNotFoundException {
final Class<?> clazz = Class.forName("com.baeldung.java.reflection.Goat");
final Class<?> clazz = Class.forName("com.baeldung.reflection.Goat");
assertEquals("Goat", clazz.getSimpleName());
assertEquals("com.baeldung.java.reflection.Goat", clazz.getName());
assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName());
assertEquals("com.baeldung.reflection.Goat", clazz.getName());
assertEquals("com.baeldung.reflection.Goat", clazz.getCanonicalName());
}
@Test
public void givenClass_whenRecognisesModifiers_thenCorrect() throws ClassNotFoundException {
final Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
final Class<?> goatClass = Class.forName("com.baeldung.reflection.Goat");
final Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal");
final int goatMods = goatClass.getModifiers();
final int animalMods = animalClass.getModifiers();
@@ -63,7 +63,7 @@ public class ReflectionUnitTest {
final Class<?> goatClass = goat.getClass();
final Package pkg = goatClass.getPackage();
assertEquals("com.baeldung.java.reflection", pkg.getName());
assertEquals("com.baeldung.reflection", pkg.getName());
}
@Test
@@ -81,8 +81,8 @@ public class ReflectionUnitTest {
@Test
public void givenClass_whenGetsImplementedInterfaces_thenCorrect() throws ClassNotFoundException {
final Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
final Class<?> goatClass = Class.forName("com.baeldung.reflection.Goat");
final Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal");
final Class<?>[] goatInterfaces = goatClass.getInterfaces();
final Class<?>[] animalInterfaces = animalClass.getInterfaces();
@@ -94,16 +94,16 @@ public class ReflectionUnitTest {
@Test
public void givenClass_whenGetsConstructor_thenCorrect() throws ClassNotFoundException {
final Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
final Class<?> goatClass = Class.forName("com.baeldung.reflection.Goat");
final Constructor<?>[] constructors = goatClass.getConstructors();
assertEquals(1, constructors.length);
assertEquals("com.baeldung.java.reflection.Goat", constructors[0].getName());
assertEquals("com.baeldung.reflection.Goat", constructors[0].getName());
}
@Test
public void givenClass_whenGetsFields_thenCorrect() throws ClassNotFoundException {
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
final Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal");
final Field[] fields = animalClass.getDeclaredFields();
final List<String> actualFields = getFieldNames(fields);
@@ -114,7 +114,7 @@ public class ReflectionUnitTest {
@Test
public void givenClass_whenGetsMethods_thenCorrect() throws ClassNotFoundException {
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
final Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal");
final Method[] methods = animalClass.getDeclaredMethods();
final List<String> actualMethods = getMethodNames(methods);
@@ -124,7 +124,7 @@ public class ReflectionUnitTest {
@Test
public void givenClass_whenGetsAllConstructors_thenCorrect() throws ClassNotFoundException {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
final Constructor<?>[] constructors = birdClass.getConstructors();
assertEquals(3, constructors.length);
@@ -132,7 +132,7 @@ public class ReflectionUnitTest {
@Test
public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
birdClass.getConstructor();
birdClass.getConstructor(String.class);
birdClass.getConstructor(String.class, boolean.class);
@@ -140,7 +140,7 @@ public class ReflectionUnitTest {
@Test
public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
final Constructor<?> cons1 = birdClass.getConstructor();
final Constructor<?> cons2 = birdClass.getConstructor(String.class);
@@ -159,7 +159,7 @@ public class ReflectionUnitTest {
@Test
public void givenClass_whenGetsPublicFields_thenCorrect() throws ClassNotFoundException {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
final Field[] fields = birdClass.getFields();
assertEquals(1, fields.length);
assertEquals("CATEGORY", fields[0].getName());
@@ -168,7 +168,7 @@ public class ReflectionUnitTest {
@Test
public void givenClass_whenGetsPublicFieldByName_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
final Field field = birdClass.getField("CATEGORY");
assertEquals("CATEGORY", field.getName());
@@ -176,7 +176,7 @@ public class ReflectionUnitTest {
@Test
public void givenClass_whenGetsDeclaredFields_thenCorrect() throws ClassNotFoundException {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
final Field[] fields = birdClass.getDeclaredFields();
assertEquals(1, fields.length);
assertEquals("walks", fields[0].getName());
@@ -184,7 +184,7 @@ public class ReflectionUnitTest {
@Test
public void givenClass_whenGetsFieldsByName_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
final Field field = birdClass.getDeclaredField("walks");
assertEquals("walks", field.getName());
@@ -192,14 +192,14 @@ public class ReflectionUnitTest {
@Test
public void givenClassField_whenGetsType_thenCorrect() throws Exception {
final Field field = Class.forName("com.baeldung.java.reflection.Bird").getDeclaredField("walks");
final Field field = Class.forName("com.baeldung.reflection.Bird").getDeclaredField("walks");
final Class<?> fieldClass = field.getType();
assertEquals("boolean", fieldClass.getSimpleName());
}
@Test
public void givenClassField_whenSetsAndGetsValue_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
final Bird bird = (Bird) birdClass.getConstructor().newInstance();
final Field field = birdClass.getDeclaredField("walks");
field.setAccessible(true);
@@ -216,7 +216,7 @@ public class ReflectionUnitTest {
@Test
public void givenClassField_whenGetsAndSetsWithNull_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
final Field field = birdClass.getField("CATEGORY");
field.setAccessible(true);
@@ -225,7 +225,7 @@ public class ReflectionUnitTest {
@Test
public void givenClass_whenGetsAllPublicMethods_thenCorrect() throws ClassNotFoundException {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
final Method[] methods = birdClass.getMethods();
final List<String> methodNames = getMethodNames(methods);
@@ -235,7 +235,7 @@ public class ReflectionUnitTest {
@Test
public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect() throws ClassNotFoundException {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
final List<String> actualMethodNames = getMethodNames(birdClass.getDeclaredMethods());
final List<String> expectedMethodNames = Arrays.asList("setWalks", "walks", "getSound", "eats");
@@ -248,24 +248,17 @@ public class ReflectionUnitTest {
@Test
public void givenMethodName_whenGetsMethod_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Method walksMethod = birdClass.getDeclaredMethod("walks");
final 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());
final Bird bird = new Bird();
final Method walksMethod = bird.getClass().getDeclaredMethod("walks");
final Method setWalksMethod = bird.getClass().getDeclaredMethod("setWalks", boolean.class);
assertTrue(walksMethod.canAccess(bird));
assertTrue(setWalksMethod.canAccess(bird));
}
@Test
public void givenMethod_whenInvokes_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
final Bird bird = (Bird) birdClass.getConstructor().newInstance();
final Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class);
final Method walksMethod = birdClass.getDeclaredMethod("walks");

Some files were not shown because too many files have changed in this diff Show More