forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
35 lines (25 loc) · 899 Bytes
/
Copy pathMain.java
File metadata and controls
35 lines (25 loc) · 899 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package modern.challenge;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Optional;
public class Main {
public static void main(String[] args) throws ReflectiveOperationException {
// Method method = Book.class.getDeclaredMethod("printNonStatic");
Method method = Book.class.getDeclaredMethod("printStatic");
Optional<Book> bookInstance = fetchBookInstance(method);
// Avoid
if (bookInstance.isPresent()) {
method.invoke(bookInstance.get());
} else {
method.invoke(null);
}
// Prefer
method.invoke(bookInstance.orElse(null));
}
private static Optional<Book> fetchBookInstance(Method method) {
if (Modifier.isStatic(method.getModifiers())) {
return Optional.empty();
}
return Optional.of(new Book());
}
}