当前位置:网站首页>Summary of empty string judgment in the project

Summary of empty string judgment in the project

2022-07-01 14:55:00 Xiaoqu classmate

In the project , I believe that many partners have been java Of NPE(Null Pointer Exception) The so-called null pointer makes you dizzy , Somebody said “ Prevent null pointer exception , It is the basic cultivation of programmers .” But cultivation belongs to cultivation , It is also one of the most troublesome problems for our programmers , So today we're going to make the most of Java8 New features Optional To simplify the code as much as possible and deal with NPE(Null Pointer Exception Null pointer exception ).

1、 know Optional And use

Simply speaking ,java Provided Opitonal Class is Java It is provided to solve the problem that we usually judge whether the object is empty , Will use null!=obj Such a way to judge the existence of , So as to solve the headache caused by NPE(Null Pointer Exception Null pointer exception ), meanwhile Optional The existence of can make the code simpler , More readable , Code is more efficient to write .

Conventional judgment :

// object   people 
// Attributes are  name,age
Person person=new Person();
if (null==person){
    
   return "person by null";
}
return person;

Use Optional:

// object   people 
// Attributes are  name,age
Person person=new Person();
return Optional.ofNullable(person).orElse("person by null");

Test presentation class Person Code ( If a friend doesn't understand, you can take a look at this ):

public class Person {
    
    private String name;
    private Integer age;

    public Person(String name, Integer age) {
    
        this.name = name;
        this.age = age;
    }

    public Person() {
    
    }

    public String getName() {
    
        return name;
    }

    public void setName(String name) {
    
        this.name = name;
    }

    public Integer getAge() {
    
        return age;
    }

    public void setAge(Integer age) {
    
        this.age = age;
    }
}

1.1、Optional objects creating

First of all, let's turn it on Optional Internal , Go and find out First create a few Optional Object extraction method .

public final class Optional<T> {
    
   private static final Optional<?> EMPTY = new Optional<>();
   private final T value;
   // We can see that both construction squares are private  Private 
   // explain   We can't go outside new come out Optional object 
   private Optional() {
    
        this.value = null;
    }
   private Optional(T value) {
    
        this.value = Objects.requireNonNull(value);
    }
    // This static method is roughly   Is to create an object with an empty wrapper value, because there is no parameter assignment 
   public static<T> Optional<T> empty() {
    
        @SuppressWarnings("unchecked")
        Optional<T> t = (Optional<T>) EMPTY;
        return t;
    }
    // This static method is roughly   Is to create an object with non empty packing value   Because of the assignment 
   public static <T> Optional<T> of(T value) {
    
        return new Optional<>(value);
    }
    // This static method is roughly   If parameters value It's empty , Create an empty object , If it's not empty , Then create a parameter object 
   public static <T> Optional<T> ofNullable(T value) {
    
        return value == null ? empty() : of(value);
    }
 }

Then make a simple example to show Corresponding to the above

// 1、 Create a wrapper object with an empty value Optional object 
Optional<String> optEmpty = Optional.empty();
// 2、 Create a wrapper object whose value is not empty Optional object 
Optional<String> optOf = Optional.of("optional");
// 3、 The value of the created wrapper object can be empty or not Optional object 
Optional<String> optOfNullable1 = Optional.ofNullable(null);
Optional<String> optOfNullable2 = Optional.ofNullable("optional");

1.2 、Optional.get() Method ( Returns the value of the object )

get() The method is to return a option Instance value of Source code :

public T get() {
    
    if (value == null) {
    
        throw new NoSuchElementException("No value present");
    }
    return value;
}

That is, if value If it is not empty, return , If it is empty, an exception is thrown “No value present” Simple examples show :

Person person=new Person();
person.setAge(2);
Optional.ofNullable(person).get();

1.3、Optional.isPresent() Method ( Judge whether it is empty )

isPresent() The method is to return a boolean Type values , True if the object is not empty , If it is empty, then false Source code :

public Boolean isPresent() {
    
    return value != null;
}

A simple example shows :

Person person=new Person();
person.setAge(2);
if (Optional.ofNullable(person).isPresent()){
    
    // Write non empty logic 
    System.out.println(" Not empty ");
} else{
    
    // Write empty logic 
    System.out.println(" It's empty ");
}

1.4、Optional.ifPresent() Method ( Judge whether it is empty and return the function )

This means that if the object is not empty , Then run the function body Source code :

  public void ifPresent(Consumer<? super T> consumer) {
    
        // If value Not empty , Then run accept Method body 
        if (value != null)
            consumer.accept(value);
    }

See examples :

Person person=new Person();
person.setAge(2);
Optional.ofNullable(person).ifPresent(p -> System.out.println(" Age "+p.getAge()));

If the object is not empty , Will print this age , Because it has been done internally NPE( Judge not empty ), So don't worry about null pointer exceptions .

1.5、Optional.filter() Method ( Filter objects )

filter() The method roughly means , Accept an object , Then filter him conditionally , If the conditions are met, return Optional Object itself , If it does not match, it returns null Optional.

Source code :

public Optional<T> filter(Predicate<? super T> predicate) {
    
    Objects.requireNonNull(predicate);
    // Return directly if it is empty this
    if (!isPresent())
                return this; else
            // Determine whether the return itself is empty Optional
    return predicate.test(value) ? this : empty();
}

A simple example :

Person person=new Person();
person.setAge(2);
Optional.ofNullable(person).filter(p -> p.getAge()>50);

1.6、Optional.map() Method ( Object is repackaged )

map() The method will correspond to Funcation Objects in functional interfaces , Perform a quadratic operation , Encapsulate it into a new object and return it in Optional in
Source code :

 public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
    
        Objects.requireNonNull(mapper);
        // If it is empty, return yourself 
        if (!isPresent())
            return empty();
        else {
    
        // Otherwise, return the method decorated Optional
            return Optional.ofNullable(mapper.apply(value));
        }
    }

Example show :

Person person1=new Person();
person.setAge(2);
String optName = Optional.ofNullable(person).map(p -> person.getName()).orElse("name It's empty ");

1.7、Optional.flatMap() Method (Optional Object is repackaged )

map() The method will correspond to Optional< Funcation > Objects in functional interfaces , Perform a quadratic operation , Encapsulate it into a new object and return it in Optional in

Source code :

public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
    
    Objects.requireNonNull(mapper);
    if (!isPresent())
                return empty(); else {
    
        return Objects.requireNonNull(mapper.apply(value));
    }
}

Example

Person person=new Person();
person.setAge(2);
Optional<Object> optName = Optional.ofNullable(person).map(p -> Optional.ofNullable(p.getName()).orElse("name It's empty "));

1.8、Optional.orElse() Method ( Null returns the object )

One of the common methods , This method means that if the wrapper object is empty , Is executed orElse In the method value, If it is not empty , The write object is returned

Source code :

public T orElse(T other) {
    
    // If it is not empty , return value, If it is empty , return other
    return value != null ? value : other;
}

1.9、Optional.orElseGet() Method ( Empty return Supplier object )

This with orElse Very similar , It's not the same as joining , The parameter for Supplier object , Null returns the of the incoming object .get() Method , If it is not empty, the current object is returned
Source code :

public T orElseGet(Supplier<? extends T> other) {
    
    return value != null ? value : other.get();
}

Example :

Optional<Supplier<Person>> sup=Optional.ofNullable(Person::new);
// call get() Method , Only then will the constructor of the object be called , Get the real object 
Optional.ofNullable(person).orElseGet(sup.get());

1.10、Optional.orElseThrow() Method ( Null returns an exception )

Personally, I often use this method in actual combat , The function of the method is if it is empty , Just throw the exception you defined , If not null, return the current object , In actual combat, all exceptions must be handled well , For code readability
Source code :

  public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
    
        if (value != null) {
    
            return value;
        } else {
    
            throw exceptionSupplier.get();
        }
    }

example : This is the actual combat source code

// A simple query 
Member member = memberService.selectByPhone(request.getPhone());
Optional.ofNullable(member).orElseThrow(() -> new ServiceException(" No relevant data to query "));
原网站

版权声明
本文为[Xiaoqu classmate]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/182/202207011453115946.html