Optional DataType JDK 8

how do you normally do a NULL check inside the java application. if you’re using older jdk, just using the if to check whether the object is null or not, something like below …

 

if(myObject != null){
... // do something
}

by using new JDK 8, there is a wrapper class that could wrap object type and basically provides some features for developers and in simple words, do the heavy lifting internally, make the code compact and more readable.

 

please check below example.


Optional<MyDataType> returnedInstance = myObjInstance.getMeSomething();

 

Notes:
1. mechanism to check whether the return type contains the NULL pointer exception or not.
2.decrease the null pointer exception thrown by the application.
3. due to suggestion by openJDK mailing list — only use the Optional in return tye
3.a: still needed to check for input params for functions and methods inside the classes.
4. Checked exception can be used with Optional to handle and signal the entier application whenever the unexpected status would be met.
5. something like this …
Optional<TypeIAmExpecting> = getMySomething(String input);

ifPresent() — return true if value is not null and would be presented.
orElse(defultValue);
get(); — get the value
isPresent() — check in ifelse statement and ha get() or handle the no-exited stateus.

when to use: as return type

 

 

Advertisements

Passing By-Value & By-Reference

for me there was a very big confusion when I tried to learn java at the beginning. so I will try to clear the situation for anyone who might have some questions about how Java treats with parameters inside its methods.

  • Method parameters as primitive type: the value will be copied into the methods scope and the result won’t affect outside the methods unless you return the result. so it’s by value.
  • Method parameters as class reference: the value will be copied into the methods scope and the result won’t affect outside the methods unless you return the result. so it’s by value.

so it shows, it doesn’t matter whether parameters of the methods are primitive types or class instance, the params will always be copied for methods and outside of the methods don’t have access to its internal changes.

if you want to take affect the by-reference you can use and update the content of the objects using references inside the method. that’s the only way I am using to change whatever I want and make that consistent outside of my methods body.

so since the parameters are immutable, any changes won’t affect outside, so for changing outside variables, the only way is to update and do the change inside the methods using the class variables itself, for example:

public void myChangerMethod(Person p1, Person p2){

// doing anything with p1 nad p2 won’t affect unless you can use these references to

Person p_temp = p1;

p1 = p2;

p2 = p_temp; // these lines won’t change anything outside of this method.

//change their object content itself. something like below:

String name_temp = p1.getName();

p1.setName(P2.getName()); // modifying content

p2.setName(name_temp); // modifying the first content.

}

 

Reflection – A Quick WrapUp :)

ok, I talked about reflection in couple posts specifically and indirectly I referred to them in a few others, but just to wrap up, Reflections are very useful and very powerful tool that every developers needed them in their toolbox. now, when you read and practice what I have explained so nfar, you can see the connections between that package with others and also you can see its footprints everywhere in Java frameworks and other utilities.

Reflection generally can be used to retrive the information about every Class Type.

you can load and reload Class definition into memory and you can trace everything inside classes, even inner classes (as I explained in my examples in Reflections)

Also Reflection will be used in Annotation processing behind the scene by JDK.

Also for Serialization, Java itself uses reflection to get the SerialVerUID fields to validate the classes.

to make that easy, I can just tell that wherever you saw something might use Class Type, you can now think of Reflection.

Serialization (Part 3) – Customized serialization and Transient Keyword

in some cases, we prefer to exclude a/ some member(s) of a class from being serialized. the way to do that is to use transient keyword in the declaration of that field. below is an example:

Why?

to decrease the space in the serialization process

Customization of serialization

make sure the Type that implement Serializable interface and you want it to be serialized, implement one or both of these two methods:


private void writeObject(ObjectOutputSteam out) throws IOException

private void readObject(ObjectInputSteam in) throws IOException, ClassNotFoundException

we can make them private since these methods could only be used by Serialization system through Reflections, so we don’t want anyone else outside of this scenario call them.

so in my example below,¬† I have added a new Char field into my type along with implementing these new methods into my User type and then re-ran the same test file that we have before ….


import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
*
* @author Unknown_
*/
public class User implements Serializable {

private static final long serialVersionUID = -607661653725142657L;

private String username, password;
private int securityCode;
private char permissionCode;

public User() {
}

public User(String username, String password) {
this.username = username;
this.password = password;

}

public void updateUsername(String username) {
System.out.println("username's changed to ... " + username);
this.username = username;
}

public void setSecurityCode(int securityCode) {
this.securityCode = securityCode;
}

@Override
public String toString() {
return "Name: " + this.username + " - passwd: " + this.password + " - SecCode: " + this.securityCode + " permissionCode: " + permissionCode;
}

public void showcontent() {
System.out.println("" + this.toString());
}

public void setPermissionCode(char permissionCode) {
this.permissionCode = permissionCode;
}



/**
* customizing the write object process
* @param out
* @throws IOException
*/
private void writeObject(ObjectOutputStream out) throws IOException{

out.defaultWriteObject();
}

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException{

ObjectInputStream.GetField readFields = in.readFields();
permissionCode = readFields.get("permissionCode", 'u'); // 'u' as undefined, instead of default compiler '\0' NULL
username = (String) readFields.get("username", null);
password = (String) readFields.get("password", null);
securityCode = readFields.get("securityCode", -1);
}

}

and the test scenario class:


&nbsp;

import com.navid.practice.serialization.banking.User;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
* we have a bank account and we want to save and then reload that into the
* object instance to see how serialization will work.
*
* @author Unknown_
*/
public class TestScenario1 {

/**
* saving objects into a file that is mentioned in the filename argument.
*
* @param u
* @param filename
*/
public static void saveUser(User u, String filename) {

try (ObjectOutputStream out = new ObjectOutputStream(Files.newOutputStream(Paths.get(filename),StandardOpenOption.APPEND))) {

out.writeObject(u);

} catch (IOException ex) {
Logger.getLogger(TestScenario1.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
}
}

/**
* reading the object from the file mentioned as filename.
*
* @param filename
* @return
*/
public static User reloadUser(String filename) {

User u = null;
try (ObjectInputStream in = new ObjectInputStream(Files.newInputStream(Paths.get(filename), StandardOpenOption.READ))) {
u = (User) in.readObject();

} catch (IOException ex) {
Logger.getLogger(TestScenario1.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(TestScenario1.class.getName()).log(Level.SEVERE, null, ex);
}
return u;
}

public static void main(String[] args) {

User u = new User("MyOldUserName", "myPasswd1");
u.setSecurityCode(1200);
u.showcontent();
u.updateUsername("myNewUsername");
u.showcontent();

System.out.println("Saving Object ... ");
saveUser(u, "myAccounts.dat");
System.out.println("Reloading Object ... ");
reloadUser("myAccounts.dat").showcontent();

}

}

output will be something like this …

run:
Name: MyOldUserName - passwd: myPasswd1 - SecCode: 1200 permissionCode: 
username's changed to ... myNewUsername
Name: myNewUsername - passwd: myPasswd1 - SecCode: 1200 permissionCode: 
Saving Object ... 
Reloading Object ... 
Name: myNewUsername - passwd: myPasswd1 - SecCode: 1200 permissionCode: u
BUILD SUCCESSFUL (total time: 0 seconds)

since we didn’t set the default value for that recently added char in out readObject method we defined a default value. so whenever serialization system couldn’t find that field’s value in file, returned us the default value of that.

 

Serialization (Part 1) – Basics

Serialization means make the object transferable :

  1. between ip addresses over a network
  2. between memory addresses
  3. into a file
  4. into a database systems

Serializable interface in java provides serialization capabilities to any object type which is implement that and all of its content instances (all of its memebers). Object graph

Serializable interface is an marker interface = does’t hvae any menthod.


import java.io.Serializable;

/**
*
* @author Unknown_
*/
public class User implements Serializable {

private String username, password;

public User() {
}

public User(String username, String password) {
this.username = username;
this.password = password;
}

public void updateUsername(String username) {
System.out.println("username's changed to ... " + username);
this.username = username;
}

@Override
public String toString() {
return "Name: " + this.username + " - passwd: " + this.password;
}

public void showcontent() {
System.out.println("" + this.toString());
}

}

so far we have made this class serializable, but how we can save and persist and also reload it from our file system?

  • ObjectInputStream
  • ObjectOutputStream

by using above calsses you can just easily drop the serilized object into the input stream or fetch them from output stream without being worried about the rest of the process and the result will be provided. Check below examples:


import com.navid.practice.serialization.banking.User;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
* we have a bank account and we want to save and then reload that into the
* object instance to see how serialization will work.
*
* @author Unknown_
*/
public class TestScenario1 {

/**
* saving objects into a file that is mentioned in the filename argument.
*
* @param ba
* @param filename
*/
public static void saveUser(User u, String filename) {

try (ObjectOutputStream out = new ObjectOutputStream(Files.newOutputStream(Paths.get(filename), StandardOpenOption.CREATE))) {

out.writeObject(u);

} catch (IOException ex) {
Logger.getLogger(TestScenario1.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
}
}

/**
* reading the object from the file mentioned as filename.
*
* @param filename
* @return
*/
public static User reloadUser(String filename) {

User u = null;
try (ObjectInputStream in = new ObjectInputStream(Files.newInputStream(Paths.get(filename), StandardOpenOption.READ))) {
u = (User) in.readObject();

} catch (IOException ex) {
Logger.getLogger(TestScenario1.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(TestScenario1.class.getName()).log(Level.SEVERE, null, ex);
}
return u;
}

public static void main(String[] args) {

User u = new User("MyOldUserName", "myPasswd1");
u.showcontent();
u.updateUsername("myNewUsername");
u.showcontent();

System.out.println("Saving Object ... ");
saveUser(u, "myAccounts.dat");
System.out.println("Reloading Object ... ");
reloadUser("myAccounts.dat").showcontent();

}

}

output will be something like this …

run:
Name: MyOldUserName - passwd: myPasswd1
username's changed to ... myNewUsername
Name: myNewUsername - passwd: myPasswd1
Saving Object ... 
Reloading Object ... 
Name: myNewUsername - passwd: myPasswd1
BUILD SUCCESSFUL (total time: 0 seconds)

Reflection Example Part 6

in the previous example, the application will work however it’s tied to target object types and worker thread’s constructor. we can make it loosely coupled in a way that releases the application from these constraints and makes that flexible to decide later in running time about what Thread worker types might come in and also we can add different workerThread in future without changing the main logic. also, another good tip is reflection is Slower than regularly compiled programming, we need to decrease the use of reflections as much as possible. below is the solution:

Interface TaskWorker:


package com.navid.practice.reflection.newsrc.worker2;

/**
* by using this class
* 1. we can have different worker as much as we want
* 2. the worker's code doesn't need to have special constructor. -- more loosely coupled.
*
* @author Unknown_
*/
interface Taskworker extends Runnable{

/**
* do the actual task, so any thread could implement this.
* implement the threading triggering process.
* @param operation
* @param amount
*/
public void doWork();

/**
* setting a target for our worker thread implemenation. this target object will be an object reference to
* a BankAccount object or anything that is extended the bankAccount object.
* @param target
*/
public void setTarget(Object target);

}

then updating worker thread

AccountWorkerImproved


package com.navid.practice.reflection.newsrc.worker2;

import com.navid.practice.reflection.legacy.beans.BankAccount;
import com.navid.practice.reflection.legacy.beans.HighVolumeAccount;

/**
*
* @author Unknown_
*/
public class AccountWorkerImproved implements Taskworker {

private BankAccount bankAccount;

@Override
public void doWork() {

//decied if that's the BankAccount normal or HighVolume one, then trigger its thread.
Thread thread  = new Thread( HighVolumeAccount.class.isInstance(bankAccount)? (HighVolumeAccount)this.bankAccount : this);

thread.start();
}

@Override
public void setTarget(Object target) {

if(BankAccount.class.isInstance(target)){
this.bankAccount = (BankAccount) target;
}else
throw new IllegalArgumentException("Target object is not matching bankAccount class");
}

@Override
public void run() {
System.out.println("WorkerThreadImproved - start processing the account deposits ... ");
}

}

Executing the Scenario


package com.navid.practice.reflection.newsrc.worker2;

import com.navid.practice.reflection.legacy.beans.BankAccount;
import com.navid.practice.reflection.legacy.beans.HighVolumeAccount;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
*
* @author Unknown_
*/
public class ReflectionPractice2 {

public void startWork(String workerTypeName, Object workerTarget) {

try {

// providing the worker thread information.
Class<?> workerType = Class.forName(workerTypeName);

// since we don't have any additional constructor beside our worker thread default one, so we don;t need to get the target types
// and call it. insteda we cna use this ...
Taskworker taskWorker = (Taskworker) workerType.newInstance();

// the the rest is like reglar programming
taskWorker.setTarget(workerTarget);
taskWorker.doWork();

} catch (ClassNotFoundException | SecurityException | IllegalArgumentException | InstantiationException | IllegalAccessException ex) {
Logger.getLogger(ReflectionPractice2.class.getName()).log(Level.SEVERE, null, ex);
}

}

public static void main(String[] args) {

BankAccount bankAccount = new BankAccount("1234", 100);

new ReflectionPractice2().startWork("com.navid.practice.reflection.newsrc.worker2.AccountWorkerImproved", bankAccount);

HighVolumeAccount highVolumeAccount = new HighVolumeAccount();

new ReflectionPractice2().startWork("com.navid.practice.reflection.newsrc.worker2.AccountWorkerImproved", highVolumeAccount);
}

}

the output of our test is exactly the same as before, but we decrease the use of reflection and also make our design clearer and loosely coupled.

run:
BankAccount Object constructor 2
BankAccount Object constructor 1 
WorkerThreadImproved - start processing the account deposits ... 
HighVolumeAccount process all Daily Deposits.
HighVolumeAccount process all Daily Withrwals.
BUILD SUCCESSFUL (total time: 0 seconds)

Reflection Invoking Members (part 4)

By Using Reflection, we can invoke methods of objects even when we don’t have the proper references to them.

for example we have some objects in the heap from specific types that we don’t even have any knowledge about their types, but we need to invoke their methods. we could call their methods, if we know their specific references from their type, but just by calling

Object.method2(), which we know method2() is only defined in object MyObject, throwing exceptions, so how we can invoke method2 when we don’t have actual reference from MyObject class? the question is simple. it can be executed by below line of code:

this is our class:


public class ClassTesting {

private int number2present = 100;

public void writeSomething(int number2Present) {

System.out.println("ClassTesting.writeSomething() ... ");
System.out.println("input: " + number2Present + " + " + this.number2present + " = " + (number2Present + this.number2present));
this.number2present += number2Present;
System.out.println("call this method via Reflection API.");
}

}

and we can call method writeSomething(int num), by using below line of code:


try {

ClassTesting.class.getMethod("writeSomething", int.class).invoke(new ClassTesting(),200);

} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(ExpressClassInfo.class.getName()).log(Level.SEVERE, null, ex);
}

output will be something like:

run:
ClassTesting.writeSomething() ... 
input: 200 + 100 = 300
call this method via Reflection API.
BUILD SUCCESSFUL (total time: 0 seconds)

Analysis:

we can get access to the Class object, then by calling getMethods and then finding the proper method and passing its proper typed parameters, we can easily invoke its methods.


Class<?> myclass = ClassTesting.class;

Method myMethod = myclass.getMethod("writeSomething", int.class);

myMethod.invoke(new ClassTesting(),200);