Notice

╠ This is my personal blog and my posts here have nothing to do with my employers or any other association I may have. It is my personal blog for my personal experience, ideas and notes. ╣
Showing posts with label preview. Show all posts
Showing posts with label preview. Show all posts

Sunday, August 9, 2020

New way to create immutable object in Java ['record'] JEP 384: Records

As a Java developer, we use POJO every day in our coding. We have to write or generate codes of accessor methods and other methods like 'equals', 'toString' and 'hashCode' or use a library like Lombok. 

To make it more simplified Java introducing 'record'. Using which developer need not have to generate or write these code. 

Some of the features of these 'record' class. 

  • implicitly they are final so it cannot be extended or abstracted but can implement an interface. 
  • java.lang.Record is the superclass of record 
  • A record cannot define the native method. 
  • A record field(s)  is/are implicitly final
Let's see with an example. 

A simple record with no boilerplate code. It provides field accessor method, 'toString', 'equals' and 'hashCode' readily available. 

A record with multiple constructors and instance method. 

A record with constructor level validation, static method and override 'equals' method. 

In this class, we are accessing the field with the internal method and other methods like 'toString', 'equals' and 'hashCode'. 


Output 

To compile these codes 

javac --enable-preview --release 15 TestRecord.java


To Run these codes 

java --enable-preview TestRecord



Happy coding and keep learning!

Saturday, July 18, 2020

JDK 15 [Pattern Matching of instanceof operator ]

This is an enhancement of Java language with pattern matching for the instanceof operator. Currently, this feature is in the second preview in JDK 15.

So currently when we need to cast an object, we check it using instanceof operation then only we cast the object to save our self from class cast exception.

existing instanceof operator

In the above code snippet, we have to explicitly cast it to an object. 
In this enhancement, we no more have to do it. 



To run the below code you need to install JDK 14 or above and have to enable the preview feature of javac & java. 
In order to enable that preview feature. 
javac 
      --enable-preview 
        -release <version> 
      <Source file>

java 
    --enable-preview 
       <Compiled class> 



Output

 Happy Coding!