Getting some kind of representation of a Lambda Expression at runtime - java

I'd like to use something like this to check some conditions, but the problem is that I need to know which condition failed and log the exception, this way does achieve it but relies on knowing the position at which it was checked inside the code which isn't ideal, is there any other nicer way of doing this? (without making calling the function much longer)
matchOrThrow(
() -> 1 == 2,
() -> 1 == 1,
() -> a > b,
() -> c == null
);
public static void matchOrThrow(BooleanSupplier... conditions) {
int i = 1;
for (BooleanSupplier condition : conditions) {
if (Boolean.FALSE.equals(condition.getAsBoolean())) {
throw new CustomException("Condition check n_" + i + " failed");
}
i++;
}
}

You might be interested at looking at the Decorator design patter.
Namely, you can create a decorating implementation of the Functional interface of your choice. It seems like you Predicate is more suitable for than a BooleanSupplier, therefore the example below illustrates a throwing Predicate, which expects a predicate, producer of the target exception, message and logger as arguments and its implementation of test() delegates to the wrapped predicate to evaluate the condition.
The instances of the trowing Predicate can be used anywhere, where Predicate is expected.
public class ThrowingLoggPredicate<T> implements Predicate<T> {
private Predicate<T> predicate;
private Function<String, RuntimeException> exceptionFactory;
private String messageShort;
private String format;
private Logger logger;
public ThrowingLoggPredicate(Predicate<T> predicate,
Function<String, RuntimeException> exceptionFactory,
String messageShort, String format,
Logger logger) {
this.predicate = predicate;
this.exceptionFactory = exceptionFactory;
this.messageShort = messageShort;
this.format = format;
this.logger = logger;
}
public boolean test(T t) {
if (!predicate.test(t)) {
RuntimeException e = exceptionFactory.apply(messageShort);
String messageVerbose = String.format(format, t);
logger.log(Level.ERROR, messageVerbose, e);
throw e;
}
return true;
}
public static <T> boolean allMatch(Collection<Predicate<T>> predicates, T t) {
return predicates.stream().allMatch(p -> p.test(t));
}
}

Related

Assert expected exception with specific criteria in custom fields

I want to verify that an expected exception meets certain criteria. Take this as a starting point:
class MyException extends RuntimeException {
int n;
public MyException(String message, int n) {
super(message);
this.n = n;
}
}
public class HowDoIDoThis {
#Rule
public ExpectedException thrown = ExpectedException.none();
#Test
public void test1() {
thrown.expect(MyException.class);
throw new MyException("x", 10);
}
}
How do I assert, for example, that the thrown exception has n > 1 and message contains only lowercase letters? I was thinking of using thrown.expect(Matcher) but can't figure out how to get a Hamcrest matcher to check arbitrary fields of an object.
A consise and neat alternative way is to use AssertJ instead of the ExpectedException rule.
assertThatThrownBy(() -> {
throw new MyException("x", 10);
})
.matches(e -> e.getMessage().equals(e.getMessage().toLower()), "message is lowercase")
.matches(e -> ((CustomException) e).n > 10, "n > 10");
You can use TypeSafeMatcher where you can provide your MyException class, and then an IntPredicate to check the n value against a condition:
public class MyExceptionMatcher extends TypeSafeMatcher<MyException> {
private final IntPredicate predicate;
public MyExceptionMatcher(IntPredicate predicate) {
this.predicate = predicate;
}
#Override
protected boolean matchesSafely(MyException item) {
return predicate.test(item.n);
}
#Override
public void describeTo(Description description) {
description.appendText("my exception which matches predicate");
}
}
Then you can expect like so:
thrown.expect(new MyExceptionMatcher(i -> i > 1));
There's also FeatureMatcher in Hamcrest that is great for creating matchers for nested "features" of objects. So in your example, you could structure it using FeatureMatcher in the following way (this is the pattern I tend to follow when creating matchers for nested fields):
public final class MyExceptionMatchers {
public static Matcher<MyException> withNthat(Matcher<Integer> nMatcher) {
return new FeatureMatcher<MyException, Integer>(nMatcher, "n", "n") {
#Override
protected Integer featureValueOf(MyException actual) {
return actual.n;
}
}
};
}
And in your test:
import static x.y.z.MyExceptionMatchers.withNthat;
import static org.hamcrest.Matchers.greaterThan;
...
thrown.expect(withNThat(greaterThan(1)));
With this layout it's very easy to add more matchers for MyException and it feels like a more "canonical" approach to build composable matchers that allow you to construct the exact matcher you want for your test case.

How to force lambda type to a specific one?

Suppose I have a function with such signature:
public static <T> List<Future<T>> invokeAll(Stream<Callable<T>> tasks) {
... submit given tasks using executor ...
}
and I have a stream of data, which should be "wrapped" into callable and passed to this function. Naive mapping like below does not work:
Stream<String> ids = Stream.of("1", "2", "3");
invokeAll(ids.map((id) -> {
// Do a long computation with given ID...
return Boolean.TRUE; // Compilation error: Type mismatch: cannot convert from Boolean to Callable<Object>
}));
One solution would be to return lambda that returns lambda:
invokeAll(ids.map((id) -> {
return () -> {
// Do a long computation with given ID...
return Boolean.TRUE;
};
}));
another (in some way equivalent) is to use helper function:
public static <T> Callable<T> createCallable(T id) {
return () -> {
return id;
};
}
invokeAll(ids.map(ThisClass::createCallable));
but maybe there is better / shorter way of doing the same? E.g. somehow tell the compiler that it needs to create a Callable that returns a given value:
invokeAll(ids.map((Function<String, Callable<Boolean>>) (id) -> {
// Do a long computation with given ID
return Boolean.TRUE;
}));
Thanks for any suggestion.
Let's ignore lambdas for a moment, because I think they're the source of the confusion. Let's use good old anonymous classes:
invokeAll(
ids.map(
new Function<String, Callable<Boolean>>()
{
#Override
public Callable<Boolean> apply(String str)
{
return new Callable<Boolean>()
{
#Override
public Boolean call() throws Exception
{
return Boolean.TRUE;
}
};
}
}
)
);
What you're effectively asking is "how I can automatically do this:"
invokeAll(
ids.map(
new Function<String, Callable<Boolean>>()
{
#Override
public Callable<Boolean> apply(String str)
{
return Boolean.TRUE;
}
}
)
);
Of course, you can't. A Boolean is not a Callable<Boolean>. So the solutions are limited to what you've already identified:
1) to use a lambda to create the Callable:
() -> Boolean.TRUE
() -> { return Boolean.TRUE; }
2) to create a method which does this for you. Such as method is likely to more verbose than option #1 so it doesn't gain you anything.
Sorry, there's no way other to automagically make this any better.

How to generalize a static clousure?

I have the following scenario: two validation Helpers
the StringValidationHelper ...
public class StringValidationHelper {
public static Validation<String> notNull =
SimpleValidation.from(s -> s != null, "must not be null.");
public static Validation<String> moreThan(int size) {
return SimpleValidation.from(
s -> s.length() >= size,
String.format ("must have more than %s chars.", size));
}
    ... // More methods (lessThan, etc)}
... and NumberValidationHelper.
public class NumberValidationHelper {
public static Validation<Number> notNull =
SimpleValidation.from(n -> n != null, "must not be null");
public static <N extends Number & Comparable<N>> Validation<N> lowerThan(N max){
return SimpleValidation.from(
n -> n.compareTo(max) == -1,
String.format("must be lower than %s.", max));
}
... // More methods like (greaterThan, etc)}
The method from is a static factory method that receives a Predicate and a message to eventual validation fails.
public class SimpleValidation<K> implements Validation<K>{
private Predicate<K> predicate;
private String onErrorMessage;
private SimpleValidation(Predicate<K> predicate, String onErrorMessage) {
this.predicate = predicate;
this.onErrorMessage = onErrorMessage;
}
public static <K> SimpleValidation<K> from(Predicate<K> predicate, String onErrorMessage){
return new SimpleValidation<>(predicate, onErrorMessage);
}
... // Omitted for simplicity
}
Thanks to the Validation interface, you can enjoy a wonderfully smooth interface
#FunctionalInterface
public interface Validation<K> {
     ... // Omitted for simplicity
     default Validation<K> and(Validation<K> other) {
         return param -> {
             ValidationResult firstResult = this.test (param);
            return ! firstResult.isValid()? firstResult: other.test(param);
        };
     }
   ... // Omitted for simplicity
}
So I can start, for example, a validation using the closure notNull.
Example: with NumberValidationHelper
public class MyValidate {
void validate(int toValidate) {
notNull.and(lowerThan(100)).test(toValidate).isValid();
}
}
This validation framework I developed based on this article.
Well, notNull enclaves a type-independent behavior, so I'd like to remove the duplication of these two helpers.
I'm not finding an obvious shape without losing the fluid interface.
Because the variable is static, you can not use generics and extend the behavior, for instance.
public abstract class GenericHelper<K> {
public static Validation<K> notNull = SimpleValidation.from(o -> o != null, "must not be null.");
}
Also it does not bother me to type Validation with Object as below:
public abstract class GenericHelper {
public static Validation<Object> notNull = SimpleValidation.from(o -> o != null, "must not be null.");
}
... because in the call chaining, it will give compilation error since the result of notNull will be a Validation< Object > and and will be expecting a Validation< Integer >
notNull.and(lowerThan(100)).test(toValidate).isValid(); //Does not compile
Is there any way to use the Java 8 function features that keep this interface flowing generically, running away from the solutions I've tried above?
thankful
You should relax the generic signature of and, allowing a Validation<T> with a more specific T as parameter, to produce a Validation<T> as result:
default <T extends K> Validation<T> and(Validation<T> other) {
return param -> {
ValidationResult firstResult = this.test(param);
return ! firstResult.isValid()? firstResult: other.test(param);
};
}
Staying with your examples, you still cannot write
void validate(int toValidate) {
notNull.and(moreThan(100)).test(toValidate).isValid();
}
as moreThan returns a Validation<String> which can not test an int, but spotting such errors is what Generics is all about (I suppose, you have another moreThan method in your actual code base which you didn’t include in your question). But the following will now work with your example:
void validate(int toValidate) {
notNull.and(lowerThan(100)).test(toValidate).isValid();
}
Sometimes, you need to test a validation of a more specific type before a more generic validation which still doesn’t work with the method shown above. One solution would be to go the same route as the JDK developers and augment Function.andThen(after) with a Function.compose(before), allowing to swap the roles
default <T extends K> Validation<T> compose(Validation<T> other) {
return param -> {
ValidationResult firstResult = other.test(param);
return ! firstResult.isValid()? firstResult: this.test(param);
};
}
Or you create a static method, which allows both arguments to have a broader type than the resulting Validation:
static <T> Validation<T> and(Validation<? super T> first, Validation<? super T> second) {
return param -> {
ValidationResult firstResult = first.test(param);
return ! firstResult.isValid()? firstResult: second.test(param);
};
}
Note that the static method can be combined with the convenient instance method, so that the caller only needs to resort to the static method when hitting the limitations of the generic signature:
#FunctionalInterface
public interface Validation<K> {
ValidationResult test(K item);
default <T extends K> Validation<T> and(Validation<T> other) {
return and(this, other);
}
static <T> Validation<T> and(Validation<? super T> first,Validation<? super T> second){
return param -> {
ValidationResult firstResult = first.test(param);
return ! firstResult.isValid()? firstResult: second.test(param);
};
}
}
So you can still write
notNull.and(lowerThan(100)).test(toValidate).isValid();
but when hitting the limitation, e.g.
Validation<Object> anotherCriteria;
…
lowerThan(100).and(anotherCriteria).test(toValidate).isValid();
does not work, you can resort to
Validation.and(lowerThan(100), anotherCriteria).test(toValidate).isValid();

Validating search parameters using predicates

I have a validate() method that checks the arguments passed in a rest url.
The arguments are linked to a model class like the following
class SearchCriteria {
String regno;
String hostid;
String domid;
String location;
String provider;
/*Getters and Setters*/
}
I have a utility class that checks if the arguments are set or not.
public class SearchCriteriaUtil {
public static boolean isRegnoSet(SearchCriteria criteria) {
return null != criteria.getRegno();
}
public static boolean isHostIdSet(SearchCriteria criteria) {
return null != criteria.getHostId();
}
/* Similarly for domid, location, provider */
}
I have a predicate that tests based on the conditions provided in the util and generates a Truth Value String
public class ParameterPredicate<T> implements Predicate<T>{
final Predicate<T> predicate;
final String sequence;
public ParameterPredicate(Predicate<T> predicate, String sequence) {
this.predicate = predicate;
this.sequence = sequence;
}
#Override
public String toString() {
return sequence;
}
#Override
public boolean test(T t) {
return predicate.test(t);
}
}
Now, based on the arguments set/notset,
regno -set, hostid -set, domid - notset, location - notset, provider - set
My Predicate should evaluate based on the conditions in SearchCriteriaUtil and set the sequence to the appropriate Truth Values...in this case "T T F F T"
In my validate method,
public void validateCriteria(SearchCriteria criteria) {
List<Predicate<SearchCriteria>> SearchCriteriaPredicate = Arrays.asList(SearchCriteriaUtil::isRegnoSet, SearchCriteriaUtil::isHostIdSet,
SearchCriteriaUtil::isDomidSet,
SearchCriteriaUtil::isLocationSet,
SearchCriteriaUtil::isProviderSet,
Collection<String> desired = Arrays.asList("T F F F F", "T F T T F", "T F T T F", "T F F F T", "T F F F T", "F T F F F");
I am not able to proceed beyond this point, I have to set the sequence and check if it exists in the desired list of truth values.
I was refering to a previous post : Filtering with truth tables
As I am new to java 8, any help is appreciated.
Instead of using a util class and dealing with Strings in order to check if a combination of criteria is valid, why not just add something like the following inside your SearchCriteria class:
public boolean hasDesiredCombination() {
return Criterion.DESIRED_COMBINATONS.contains(
Arrays.stream(Criterion.values())
.filter(s -> s.predicate.test(this))
.collect(Collectors.toCollection(
() -> EnumSet.noneOf(Criterion.class)))
);
}
private static enum Criterion {
REGNO(s -> s.regno != null),
HOSTID(s -> s.hostid != null),
DOMID(s -> s.domid != null),
LOCATION(s -> s.location != null),
PROVIDER(s -> s.provider != null);
private static Set<Set<Criterion>> DESIRED_COMBINATONS =
new HashSet<>(Arrays.asList(
EnumSet.of(REGNO),
EnumSet.of(REGNO, DOMID, LOCATION),
EnumSet.of(REGNO, PROVIDER),
EnumSet.of(HOSTID)
));
private Predicate<SearchCriteria> predicate;
private Criterion(Predicate<SearchCriteria> predicate) {
this.predicate = predicate;
}
}
Advantages:
You don't necessarily have to expose getters and setters
It's immediately clear from the source code which combinations are desired
The logic is where it belongs: (indirectly) inside the SearchCriteria class
I'm not sure what the purpose of ParameterPredicate is, but if I've understood correctly, you want check whether a combination of validations (SearchCriteriaPredicate) matches one of a predefined set (desired). If so, this should do it:
String sequence = SearchCriteriaPredicate.stream()
.map(p -> p.test(criteria) ? "T" : "F")
.collect(Collectors.joining(" "));
return desired.contains(sequence);

Java "?" Operator for checking null - What is it? (Not Ternary!)

I was reading an article linked from a slashdot story, and came across this little tidbit:
Take the latest version of Java, which
tries to make null-pointer checking
easier by offering shorthand syntax
for the endless pointer testing. Just
adding a question mark to each method
invocation automatically includes a
test for null pointers, replacing a
rat's nest of if-then statements, such
as:
public String getPostcode(Person person) {
String ans= null;
if (person != null) {
Name nm= person.getName();
if (nm!= null) {
ans= nm.getPostcode();
}
}
return ans
}
With this:
public String getFirstName(Person person) {
return person?.getName()?.getGivenName();
}
I've scoured the internet (okay, I spent at least 15 minutes googling variations on "java question mark") and got nothing. So, my question: is there any official documentation on this? I found that C# has a similar operator (the "??" operator), but I'd like to get the documentation for the language I'm working in. Or, is this just a use of the ternary operator that I've never seen before.
Thanks!
EDIT: Link to the article: http://infoworld.com/d/developer-world/12-programming-mistakes-avoid-292
The original idea comes from groovy. It was proposed for Java 7 as part of Project Coin: https://wiki.openjdk.java.net/display/Coin/2009+Proposals+TOC (Elvis and Other Null-Safe Operators), but hasn't been accepted yet.
The related Elvis operator ?: was proposed to make x ?: y shorthand for x != null ? x : y, especially useful when x is a complex expression.
This syntax does not exist in Java, nor is it slated to be included in any of the upcoming versions that I know of.
[EDIT]
Upon further thought, I figured out that it is actually possible to achieve the same only using standard Java 8 classes:
public String getFirstName(Person person) {
return Optional.ofNullable(person)
.map(Person::getName)
.map(Name::getGivenName)
.orElse(null);
}
In this case, it is even possible to choose a default value (like "<no first name>") instead of null by passing it as parameter of orElse.
[Original Answer]
One way to workaround the lack of "?" operator using Java 8 without the overhead of try-catch (which could also hide a NullPointerException originated elsewhere, as mentioned) is to create a class to "pipe" methods in a Java-8-Stream style.
public class Pipe<T> {
private T object;
private Pipe(T t) {
object = t;
}
public static<T> Pipe<T> of(T t) {
return new Pipe<>(t);
}
public <S> Pipe<S> after(Function<? super T, ? extends S> plumber) {
return new Pipe<>(object == null ? null : plumber.apply(object));
}
public T get() {
return object;
}
public T orElse(T other) {
return object == null ? other : object;
}
}
Then, the given example would become:
public String getFirstName(Person person) {
return Pipe.of(person)
.after(Person::getName)
.after(Name::getGivenName)
.get();
}
Java does not have the exact syntax but as of JDK-8, we have the Optional API with various methods at our disposal. So, the C# version with the use of null conditional operator:
return person?.getName()?.getGivenName();
can be written as follows in Java with the Optional API:
return Optional.ofNullable(person)
.map(e -> e.getName())
.map(e -> e.getGivenName())
.orElse(null);
if any of person, getName or getGivenName is null then null is returned.
There was a proposal for it in Java 7, but it was rejected:
http://tech.puredanger.com/java7/#null
See: https://blogs.oracle.com/darcy/project-coin:-the-final-five-or-so (specifically "Elvis and other null safe operators").
The result is that this feature was considered for Java 7, but was not included.
That's actually Groovy's safe-dereference operator. You can't use it in pure Java (sadly), so that post is simply wrong (or more likely slightly misleading, if it's claiming Groovy to be the "latest version of Java").
As lot of answers mentioned Java language don't have this feature.
It is possible in few scenarios with this compiler plugin, with few limitations
In the example code you mentioned can be written as
public String getFirstName(Person person) {
#NullSafe
String retVal = person.getName().getGivenName();
return retVal;
}
PS: I am author of plugin
It is possible to define util methods which solves this in an almost pretty way with Java 8 lambda.
This is a variation of H-MANs solution but it uses overloaded methods with multiple arguments to handle multiple steps instead of catching NullPointerException.
Even if I think this solution is kind of cool I think I prefer Helder Pereira's seconds one since that doesn't require any util methods.
void example() {
Entry entry = new Entry();
// This is the same as H-MANs solution
Person person = getNullsafe(entry, e -> e.getPerson());
// Get object in several steps
String givenName = getNullsafe(entry, e -> e.getPerson(), p -> p.getName(), n -> n.getGivenName());
// Call void methods
doNullsafe(entry, e -> e.getPerson(), p -> p.getName(), n -> n.nameIt());
}
/** Return result of call to f1 with o1 if it is non-null, otherwise return null. */
public static <R, T1> R getNullsafe(T1 o1, Function<T1, R> f1) {
if (o1 != null) return f1.apply(o1);
return null;
}
public static <R, T0, T1> R getNullsafe(T0 o0, Function<T0, T1> f1, Function<T1, R> f2) {
return getNullsafe(getNullsafe(o0, f1), f2);
}
public static <R, T0, T1, T2> R getNullsafe(T0 o0, Function<T0, T1> f1, Function<T1, T2> f2, Function<T2, R> f3) {
return getNullsafe(getNullsafe(o0, f1, f2), f3);
}
/** Call consumer f1 with o1 if it is non-null, otherwise do nothing. */
public static <T1> void doNullsafe(T1 o1, Consumer<T1> f1) {
if (o1 != null) f1.accept(o1);
}
public static <T0, T1> void doNullsafe(T0 o0, Function<T0, T1> f1, Consumer<T1> f2) {
doNullsafe(getNullsafe(o0, f1), f2);
}
public static <T0, T1, T2> void doNullsafe(T0 o0, Function<T0, T1> f1, Function<T1, T2> f2, Consumer<T2> f3) {
doNullsafe(getNullsafe(o0, f1, f2), f3);
}
class Entry {
Person getPerson() { return null; }
}
class Person {
Name getName() { return null; }
}
class Name {
void nameIt() {}
String getGivenName() { return null; }
}
I'm not sure this would even work; if, say, the person reference was null, what would the runtime replace it with? A new Person? That would require the Person to have some default initialization that you'd expect in this case. You may avoid null reference exceptions but you'd still get unpredictable behavior if you didn't plan for these types of setups.
The ?? operator in C# might be best termed the "coalesce" operator; you can chain several expressions and it will return the first that isn't null. Unfortunately, Java doesn't have it. I think the best you could do is use the ternary operator to perform null checks and evaluate an alternative to the entire expression if any member in the chain is null:
return person == null ? ""
: person.getName() == null ? ""
: person.getName().getGivenName();
You could also use try-catch:
try
{
return person.getName().getGivenName();
}
catch(NullReferenceException)
{
return "";
}
There you have it, null-safe invocation in Java 8:
public void someMethod() {
String userName = nullIfAbsent(new Order(), t -> t.getAccount().getUser()
.getName());
}
static <T, R> R nullIfAbsent(T t, Function<T, R> funct) {
try {
return funct.apply(t);
} catch (NullPointerException e) {
return null;
}
}
If someone is looking for an alternative for old java versions, you can try this one I wrote:
/**
* Strong typed Lambda to return NULL or DEFAULT VALUES instead of runtime errors.
* if you override the defaultValue method, if the execution result was null it will be used in place
*
*
* Sample:
*
* It won't throw a NullPointerException but null.
* <pre>
* {#code
* new RuntimeExceptionHandlerLambda<String> () {
* #Override
* public String evaluate() {
* String x = null;
* return x.trim();
* }
* }.get();
* }
* <pre>
*
*
* #author Robson_Farias
*
*/
public abstract class RuntimeExceptionHandlerLambda<T> {
private T result;
private RuntimeException exception;
public abstract T evaluate();
public RuntimeException getException() {
return exception;
}
public boolean hasException() {
return exception != null;
}
public T defaultValue() {
return result;
}
public T get() {
try {
result = evaluate();
} catch (RuntimeException runtimeException) {
exception = runtimeException;
}
return result == null ? defaultValue() : result;
}
}
You can test the code which you have provided and it will give syntax error.So, it is not supported in Java.
Groovy does support it and it was proposed for Java 7 (but never got included).
However, you can use the Optional provided in Java 8. This might help you in achieving something on similar line.
https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html
http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html
Example Code for Optional
STEP-1 : Use this generic method.
public static <T> Optional<T> optionalChaining(Supplier<T> resolver) {
try {
T result = resolver.get();
return Optional.ofNullable(result);
} catch (NullPointerException e) {
return Optional.empty();
}
}
STEP-2 one example of usage of this method is below
Optional<String> rs = optionalChaining(()-> user.getName("Talha").getLastName());
if(rs.isPresent()) {
}
Done !!
Since Android does not support Lambda Functions unless your installed OS is >= 24, we need to use reflection.
// Example using doIt function with sample classes
public void Test() {
testEntry(new Entry(null));
testEntry(new Entry(new Person(new Name("Bob"))));
}
static void testEntry(Entry entry) {
doIt(doIt(doIt(entry, "getPerson"), "getName"), "getName");
}
// Helper to safely execute function
public static <T,R> R doIt(T obj, String methodName) {
try {
if (obj != null)
return (R)obj.getClass().getDeclaredMethod(methodName).invoke(obj);
} catch (Exception ignore) {
}
return null;
}
// Sample test classes
static class Entry {
Person person;
Entry(Person person) { this.person = person; }
Person getPerson() { return person; }
}
static class Person {
Name name;
Person(Name name) { this.name = name; }
Name getName() { return name; }
}
static class Name {
String name;
Name(String name) { this.name = name; }
String getName() {
System.out.print(" Name:" + name + " ");
return name;
}
}
}
If this is not a performance issue for you, you can write
public String getFirstName(Person person) {
try {
return person.getName().getGivenName();
} catch (NullPointerException ignored) {
return null;
}
}

Categories

Resources