Sunday, 27 May 2018

isInstance(): Check object compatibility of a class

'isInstance()' method is used to check whether the specified object is assignment-compatible with the object represented by this Class. It is the dynamic equivalent of 'instanceof' operator.

By using 'isInstance()', instanceof operator, you can check whether the object can be casted to other type or not.

For example, let’s see the definition of Integer class, it looks like below.



public final class Integer extends Number implements Comparable<Integer> {

}

As you see, Integer is a subclass of Number, Comparable, and Object (Object is the super class for all the classes). Now if you define, an integer variable, you can assign it to Number, Comparable and Object types. You can check this compatibility using 'isInstance' method.

Test.java

package com.sample.test;

public class Test {

 public static void main(String args[]) {

  Integer var1 = new Integer(10);

  System.out.println("Can I assign var1 to Integer : " + Integer.class.isInstance(var1));
  System.out.println("Can I assign var1 to Number : " + Number.class.isInstance(var1));
  System.out.println("Can I assign var1 to Comparable : " + Comparable.class.isInstance(var1));
  System.out.println("Can I assign var1 to Object : " + Object.class.isInstance(var1));

  System.out.println("Can I assign var1 to Double : " + Double.class.isInstance(var1));
  System.out.println("Can I assign var1 to Float : " + Float.class.isInstance(var1));
 }
}

Output

Can I assign var1 to Integer : true
Can I assign var1 to Number : true
Can I assign var1 to Comparable : true
Can I assign var1 to Object : true
Can I assign var1 to Double : false
Can I assign var1 to Float : false


Previous                                                 Next                                                 Home

How to check given object is primitive or not?

'java.lang.Class' provides 'isPrimitive()' method that is used to check whether given type is a primitive type or not.

public native boolean isPrimitive();
This method returns true, if object represents a primitive type, void type. 



Java has 8 primitive types.
a.   Boolean
b.   Byte
c.   Short
d.   Int
e.   Long
f.    Float
g.   Double
h.   Char

How to check primitive types?
Below statement checks whether given type is primitive or not.

boolean.class.isPrimitive()
byte.class.isPrimitive()
short.class.isPrimitive()
int.class.isPrimitive()
long.class.isPrimitive()
float.class.isPrimitive()
double.class.isPrimitive()
char.class.isPrimitive()

Test.java

package com.sample.test;

public class Test {

 public static void main(String args[]) {

  System.out.printf("Is 'boolean' primitive ? %b\n", boolean.class.isPrimitive());
  System.out.printf("Is 'byte' primitive ? %b\n", byte.class.isPrimitive());
  System.out.printf("Is 'short' primitive ? %b\n", short.class.isPrimitive());
  System.out.printf("Is 'int' primitive ? %b\n", int.class.isPrimitive());
  System.out.printf("Is 'long' primitive ? %b\n", long.class.isPrimitive());
  System.out.printf("Is 'float' primitive ? %b\n", float.class.isPrimitive());
  System.out.printf("Is 'double' primitive ? %b\n", double.class.isPrimitive());
  System.out.printf("Is 'char' primitive ? %b\n", char.class.isPrimitive());
 }
}


Output

Is 'boolean' primitive ? true
Is 'byte' primitive ? true
Is 'short' primitive ? true
Is 'int' primitive ? true
Is 'long' primitive ? true
Is 'float' primitive ? true
Is 'double' primitive ? true
Is 'char' primitive ? true

How to check wrapper types primitiveness?
Every primitive type has a correspondent wrapper type in java.

Primitive Type
Wrapper Type
byte
Byte
short
Short
int
Integer
long
Long
float
Float
double
Double
char
Character
boolean
Boolean

All the wrapper types are the sub classes of Object class, these are not primitive types.


Test.java

package com.sample.test;

public class Test {

 public static void main(String args[]) {

  Integer var1 = new Integer(10);

  System.out.printf("Is 'var1' primitive ? %b\n", var1.getClass().isPrimitive());

 }
}


Output
Is 'var1' primitive ? false

As you see the output, isPrimitive() method is returning false on Integer type.

Below application checks wrapper types primitiveness.


Test.java

package com.sample.test;

import java.util.HashSet;
import java.util.Set;

public class Test {

 private static final Set<Class<?>> PRIMITIVE_WRAPPER_MAP = new HashSet<>();

 static {
  loadPrimitiveWrapperMap();
 }

 private static void loadPrimitiveWrapperMap() {
  PRIMITIVE_WRAPPER_MAP.add(Boolean.class);
  PRIMITIVE_WRAPPER_MAP.add(Character.class);
  PRIMITIVE_WRAPPER_MAP.add(Byte.class);
  PRIMITIVE_WRAPPER_MAP.add(Short.class);
  PRIMITIVE_WRAPPER_MAP.add(Integer.class);
  PRIMITIVE_WRAPPER_MAP.add(Long.class);
  PRIMITIVE_WRAPPER_MAP.add(Float.class);
  PRIMITIVE_WRAPPER_MAP.add(Double.class);
  PRIMITIVE_WRAPPER_MAP.add(Void.class);

 }

 /**
  * This method return true, if the class is one of below types, else false.
  * <ol>
  * <li>Byte</li>
  * <li>Short</li>
  * <li>Integer</li>
  * <li>Long</li>
  * <li>Float</li>
  * <li>Double</li>
  * <li>Boolean</li>
  * <li>Character</li>
  * </ol>
  * 
  * @param clazz
  * @return
  */
 public static boolean isPrimitiveWrapper(Class<?> clazz) {
  return PRIMITIVE_WRAPPER_MAP.contains(clazz);
 }

 public static void main(String args[]) {

  Integer var1 = new Integer(10);

  System.out.printf("Is 'var1' primitive ? %b\n", isPrimitiveWrapper(var1.getClass()));

 }
}


Output
Is 'var1' primitive ? true



Previous                                                 Next                                                 Home

Constructor: Define an object using constructor arguments

‘java.lang.reflect.Constructor’ class provides ‘newInstance’ method to create an instance of an object.

public T newInstance(Object ... initargs)
Based on the arguments, it instantiates an object.

For example,

Employee.java
package com.sample.model;

public class Employee {

 private int id;
 private String name;

 public Employee() {

 }

 public Employee(int id, String name) {
  this.id = id;
  this.name = name;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

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

 @Override
 public String toString() {
  return "Employee [id=" + id + ", name=" + name + "]";
 }

}


Below step-by-step procedure explains how to create an object to the class Employee using parameterized constructor.

Step 1: Get all the constructors of the class Employee.
Constructor<Employee>[] constructors = (Constructor<Employee>[]) Employee.class.getConstructors();

Step 2: Check the number of parameters on each constructor, if number of parameters are 2, then create an employee object by calling newInstance method.

Employee emp = null;
for (Constructor<Employee> constructor : constructors) {
 int parametersLength = constructor.getParameterTypes().length;
   
 if (parametersLength != 2)
  continue;

 emp = constructor.newInstance(1, "Hari Krishna");
}

Test.java

package com.sample.test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import com.sample.model.Employee;

public class Test {

 public static void main(String args[]) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
  Constructor<Employee>[] constructors = (Constructor<Employee>[]) Employee.class.getConstructors();

  Employee emp = null;
  for (Constructor<Employee> constructor : constructors) {
   int parametersLength = constructor.getParameterTypes().length;
   if (parametersLength != 2)
    continue;

   emp = constructor.newInstance(1, "Hari Krishna");
  }
  
  System.out.println(emp);
 }
}


Output
Employee [id=1, name=Hari Krishna]

In this case, the example is very simple, in real world, you may have to check number of arguments, type and order of the arguments also.


Previous                                                 Next                                                 Home

newInstance(): Create an instance of the class

java.lang.Class provides ‘newInstance’ method to create an object to a class. The class must have default constructor to get an instance.

Employee.java
package com.sample.model;

public class Employee {

 private int id;
 private String name;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

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

 @Override
 public String toString() {
  return "Employee [id=" + id + ", name=" + name + "]";
 }

}

Test.java

package com.sample.test;

import com.sample.model.Employee;

public class Test {

 public static void main(String args[]) throws InstantiationException, IllegalAccessException {
  Class<Employee> clazz = Employee.class;

  Employee emp = clazz.newInstance();

  System.out.println(emp);
 }
}


When you ran ‘Test.java’, you can able to below messages in console.

Employee [id=0, name=null]

As you see, I do not provide any constructor to the class Employee. If a class do not have any constructor, then java provides default constructor.

‘newInstance’ method calls the default constructor and create the object. Let’s confirm this behavior with small experiment.

Employee.java

package com.sample.model;

public class Employee {

 private int id;
 private String name;
 
 public Employee() {
  System.out.println("Default constructor of employee is called");
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

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

 @Override
 public String toString() {
  return "Employee [id=" + id + ", name=" + name + "]";
 }

}

I added a default constructor and prints a message. When I ran Test.java, you can able to see below messages in the console.

Default constructor of employee is called
Employee [id=0, name=null]


Previous                                                 Next                                                 Home

When is InstantiationException thrown?

This exception thrown, when you try to create an object by using 'newInstance' method of java.lang.Class, but the object creation to that class is not possible.

The creation of the new object can fail, because of below reasons.
a.   When you try to create an object for an abstract class, interface, array, to a primitive type (or) void.

b.   When the class do not have default constructor.

Employee.java

package com.sample.model;

public abstract class Employee {

 private int id;
 private String name;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

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

 @Override
 public String toString() {
  return "Employee [id=" + id + ", name=" + name + "]";
 }

}

Test.java

package com.sample.test;

import com.sample.model.Employee;

public class Test {

 public static void main(String args[]) throws InstantiationException, IllegalAccessException {
  Class<Employee> clazz = Employee.class;

  Employee emp = clazz.newInstance();

 }
}


I defined ‘Employee’ as an abstract class. When I try to create an object to the Employee class, I got ‘InstantiationException’.

Exception in thread "main" java.lang.InstantiationException
         at sun.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:48)
         at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
         at java.lang.Class.newInstance(Class.java:442)
         at com.sample.test.Test.main(Test.java:10)


Previous                                                 Next                                                 Home

Saturday, 26 May 2018

JavaFX: How to check whether radio button is selected or not

By calling the method 'isSelected' on RadioButton object, we can check whether radio button is selected or not.

Ex
RadioButton button1 = new RadioButton();
button1.setText("Radio Button1");
button1.setSelected(true);
System.out.println("Is radio button selected : " + button1.isSelected());

Find the below working application.

RadioButtonApp.java
package com.sample.demos;

import static javafx.geometry.Pos.CENTER;

import java.io.FileNotFoundException;
import java.net.MalformedURLException;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.RadioButton;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class RadioButtonApp extends Application {

 @Override
 public void start(Stage primaryStage) throws FileNotFoundException, MalformedURLException {

  RadioButton button1 = new RadioButton();
  button1.setText("Radio Button1");
  button1.setSelected(true);
  System.out.println("Is radio button selected : " + button1.isSelected());
  
  VBox vBox = new VBox(10, button1);
  vBox.setAlignment(CENTER);

  Scene scene = new Scene(vBox, 400, 400);

  /* Set the scene to primaryStage, and call the show method */
  primaryStage.setTitle("JavaFX Radio Button Example");
  primaryStage.setScene(scene);
  primaryStage.show();
 }

}

TestFX.java

package com.sample.demos;

import javafx.application.Application;

public class TestFX {
 public static void main(String args[]) {
  Application.launch(RadioButtonApp.class, args);
 }
}

When you ran above application, you can able to see the output "Is radio button selected : true" in console.


Previous                                                 Next                                                 Home

Friday, 25 May 2018

javaFX: RadioButton: select the radio button by default

By calling 'setSelected(true)' method on RadioButton object, you can make the radio button selected.

Ex
RadioButton button1 = new RadioButton();
button1.setText("Radio Button1");
button1.setSelected(true);

Find the below working application

RadioButtonApp.java
package com.sample.demos;

import static javafx.geometry.Pos.CENTER;

import java.io.FileNotFoundException;
import java.net.MalformedURLException;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.RadioButton;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class RadioButtonApp extends Application {

 @Override
 public void start(Stage primaryStage) throws FileNotFoundException, MalformedURLException {

  RadioButton button1 = new RadioButton();
  button1.setText("Radio Button1");
  button1.setSelected(true);

  VBox vBox = new VBox(10, button1);
  vBox.setAlignment(CENTER);

  Scene scene = new Scene(vBox, 400, 400);

  /* Set the scene to primaryStage, and call the show method */
  primaryStage.setTitle("JavaFX Radio Button Example");
  primaryStage.setScene(scene);
  primaryStage.show();
 }

}

TestFX.java
package com.sample.demos;

import javafx.application.Application;

public class TestFX {
 public static void main(String args[]) {
  Application.launch(RadioButtonApp.class, args);
 }
}




Previous                                                 Next                                                 Home