当前位置:网站首页>Promise me not to use if (obj! = null) to judge empty
Promise me not to use if (obj! = null) to judge empty
2022-06-22 01:22:00 【hello-java-maker】
Recommended today
It's best for people who can't sleep at night 8 Website , Suggest collection
23 Popular explanation of three design patterns , It's a little dirty , But I don't know
Please uninstall this product now IDEA plug-in unit !
SQL Automatic inspection artifact , Don't worry about SQL Something went wrong , Automatic completion 、 Rollback and other functions
newest 955 List of companies that don't work overtime (2022 edition )1. Preface
I believe many friends have been java Of NPE(Null Pointer Exception) The so-called null pointer makes you dizzy , Somebody said “ prevent NPE, It is the basic cultivation of programmers .” But cultivation belongs to cultivation , It is also one of the biggest headaches 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 )
2. know Optional And use
Simply speaking ,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 , It's a headache and leads to NPE(Null Pointer Exception Null pointer exception ), meanwhile Optional The existence of can make the code simpler , High readability , 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;
}
}below , Let's learn the magic Optional class !
2.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");We're about creating Optional The internal methods of the object are roughly analyzed Then we officially enter Optional In learning and using
2.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();2.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 ");
}2.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
2.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();
}Simple example :
Person person=new Person();
person.setAge(2);
Optional.ofNullable(person).filter(p -> p.getAge()>50);2.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 ");2.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 "));2.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;
}example :
Person person1=new Person();
person.setAge(2);
Optional.ofNullable(person).orElse(new Person(" Xiao Ming ", 2));2.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()); Seriously, for Supplier I was stunned by the object , Go to the Internet for a simple check to know Supplier It's also a way to create objects , Simply speaking ,Suppiler It's an interface , Is similar to Spring Lazy loading , After the declaration, it does not occupy memory , Only execution get() After method , Will call the constructor to create the object The syntax for creating objects is Supplier<Person> supPerson= Person::new; When needed supPerson.get() that will do
2.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 "));2.11 Similar methods for comparative analysis
Maybe my friends see this , If you don't use it, you will feel orElse() and orElseGet() also orElseThrow() Very similar ,map() and flatMap() So similar Ha ha ha, don't worry , It's all from this step , Let me summarize the similarities and differences of different methods orElse() and orElseGet() and orElseThrow() The differences and similarities
“The effect of this method is similar to , If the object is not empty , Then return the object , If it is empty , Return the corresponding parameter in the method body , So we can see that the parameters in these three methods are different orElse(T object ) orElseGet(Supplier < T > object ) orElseThrow( abnormal )
map() and orElseGet The differences and similarities
“The effect of this method is similar to , Secondary packaging of method parameters , And back to , It's different to join map(function function ) flatmap(Optional< function > function )
How to use it , It should be defined according to business scenarios and code specifications , Let's take a brief look at how I use the magic Optional
3. The actual combat scene reappeared
scene 1: stay service Layer Query an object , After returning, judge whether it is empty and handle it
// Query an object
Member member = memberService.selectByIdNo(request.getCertificateNo());
// Use ofNullable Add orElseThrow Do judgment and operation
Optional.ofNullable(member).orElseThrow(() -> new ServiceException(" No relevant data to query "));scene 2: We can do it in dao When defining the return value in the interface layer, add Optional for example : I'm using jpa, The same goes for others
public interface LocationRepository extends JpaRepository<Location, String> {
Optional<Location> findLocationById(String id);
}But it is Service in
public TerminalVO findById(String id) {
// This method is dao Layer is also used Optional Packaged
Optional<Terminal> terminalOptional = terminalRepository.findById(id);
// Use it directly isPresent() Determine whether it is null
if (terminalOptional.isPresent()) {
// Use get() Method to get the object value
Terminal terminal = terminalOptional.get();
// In actual combat , We've eliminated the use of set It's tedious to assign values , Direct use BeanCopy To assign
TerminalVO terminalVO = BeanCopyUtils.copyBean(terminal, TerminalVO.class);
// call dao The layer method returns the wrapped object
Optional<Location> location = locationRepository.findLocationById(terminal.getLocationId());
if (location.isPresent()) {
terminalVO.setFullName(location.get().getFullName());
}
return terminalVO;
}
// Don't forget to throw an exception
throw new ServiceException(" The terminal does not exist ");
}There are many actual combat scenes , Include return You can determine whether to return the current value or jump to another method body , What's more , If you don't have experience, you still want to learn , You can comment. I'll reply to you
4. Optional Precautions for use
Optional It's so easy to use , It can really replace if Judge ? I think it must be after you use it Optional The idea that might follow , The answer is No Take the simplest chestnut : Example 1: If I just want to judge whether a variable of an object is empty and make a judgment ?
Person person=new Person();
person.setName("");
persion.setAge(2);
// Ordinary judgment
if(StringUtils.isNotBlank(person.getName())){
// The name is not empty, execute code block
}
// Use Optional Do judgment
Optional.ofNullable(person).map(p -> p.getName()).orElse("name It's empty ");I think this example can well illustrate this problem , It's just a very simple judgment , If used Optional We also need to consider the packing value , Consider code writing , Consider method calls , Although it's only one line , But readability is not good , If other programmers read , I don't think so if It's obvious
5. Jdk 9 Yes Optional Optimize
First of all, three methods are added : or()、ifPresentOrElse() and stream().or() And orElse And so on , If the object is not empty, return the object , If it is empty, return or() Method .ifPresentOrElse() Method has two parameters : One Consumer And a Runnable. If the object is not empty , Will execute Consumer The action of , Otherwise run Runnable. comparison ifPresent() More OrElse Judge .stream() take Optional convert to stream, If there is a value, return the stream, If it's not worth it , Just go back to the empty stream.
Because of this Jdk 9 Of Optional Specifically, I didn't test , At the same time also found that there are very good articles have been able to let you understand Jdk 9 Of option The optimization of the , I'm not going to go into it .
source :juejin.cn/post/
6844904154075234318
Last , I'd like to recommend another GitHub project , The project has sorted out thousands of commonly used technical PDF, Technical books can be found here .
GitHub Address :https://github.com/hello-go-maker/cs-books
The ebook has been updated , Take it with you , Remember to order one star, Ongoing update ...边栏推荐
- Unlovable STL
- clean,compile,build,install,package区别
- [工程构建] cmake创建Release和Debug工程
- Simple sorting of RNN
- 香橙派orangepi4b上安装tensorflow与transformer
- [redis] install redis in Ubuntu and the basic usage and configuration of redis
- Idea prompt 'optional Get() 'without' ispresent() 'check error.
- Precautions for using timestamp type of SQLite3 database
- BigDecimal基本使用
- 03 FastJson 解决循环引用
猜你喜欢

03 fastjson resolving circular references

Pytorch learning 03: tensor data types and some operations

Spark RDD case: word frequency statistics

动态规划-01背包,分割等和子集,最后一块石头的重量

Planification dynamique - 01 sac à dos, partitions et sous - ensembles, poids de la dernière pierre

3分钟,带你玩转聊天机器人自动化【顶级模板】

Yolov3 3D semantic point cloud paper reading

Pytorch learning 09: basic matrix operations

【Redis】事件驱动框架源码分析(单线程)

从简单实例来看 left join 如何去重
随机推荐
The appearance, space, safety and power are all upgraded. The xinjietu x70s will be put on the market from 87900 yuan
Pytorch learning 05: indexing and slicing
2. add two numbers
4275. Dijkstra序列
Pytorch learning 01: gradient descent for simple linear regression
Pytorch learning 07:broadcast broadcast - automatic extension
[glib][gstreamer] plug in writing ideas -- inheritance, override and virtual functions
clean,compile,build,install,package区别
[dailyfresh] course record
[project construction] cmake create release and debug projects
Shardingsphere-proxy-5.0.0 implementation of distributed hash modulo fragmentation (4)
想加入大厂?看这篇文章也许会帮助到你
Special survey of moving average strategy
ShardingSphere-proxy-5.0.0分布式哈希取模分片实现(四)
Leetcode content
从简单实例来看 left join 如何去重
如何让自己的网站快速被搜索引擎找到
Virtual variables and formatting characters in debugging
BigDecimal basic use
Idea prompt 'optional Get() 'without' ispresent() 'check error.