Showing posts with label object. Show all posts
Showing posts with label object. Show all posts

Friday, 11 November 2022

How to check the type or object is a map or not?

Using Class.isAssignableFrom method, we can check whether given object is a map or not.

 

Signature

public native boolean isAssignableFrom(Class<?> cls)


'isAssignableFrom' method return true, if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter, else false.

 

Example

public static boolean isMap(final Class<?> clazz) {
	return clazz != null && (Map.class.isAssignableFrom(clazz));
}

 

Above snippet return true, if the given type a map, else false.

 


Find the below working application.

 

MapCheckDemo.java

package com.sample.app.collections;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class MapCheckDemo {

	public static boolean isMap(final Class<?> clazz) {
		return clazz != null && (Map.class.isAssignableFrom(clazz));
	}

	public static void main(String[] args) {
		final Object obj1 = Arrays.asList(2, 3, 5, 7);
		final Object obj2 = new HashMap<>();

		System.out.println("Is obj1 map : " + isMap(obj1.getClass()));
		System.out.println("Is obj2 map : " + isMap(obj2.getClass()));
	}

}

 

Output

Is obj1 map : false
Is obj2 map : true

 

   

You may like

Interview Questions

Collection programs in Java

Array programs in Java

How to check the object is an iterable or not?

Get the string representation of array by given delimiter in Java

Get an iterator from array in Java

Get reverse iterator for the given array in Java

Convert primitive array to wrapper array in Java

Friday, 23 September 2022

Jackson: Get TOML from Java object

Step 1: Get an instance of TomlMapper.

TomlMapper mapper = new TomlMapper();

 

Step 2: Serialize java object to string using writeValueAsString method.

String toml = mapper.writeValueAsString(emp);

 

Find the below working application.

 

Employee.java

 

package com.sample.app.dto;

public class Employee {
	private int id;

	private String firstName;

	private String lastName;

	public int getId() {
		return id;
	}

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

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

}

ObjectToToml.java

package com.sample.app;

import java.io.IOException;

import com.fasterxml.jackson.dataformat.toml.TomlMapper;
import com.sample.app.dto.Employee;

public class ObjectToToml {

	public static void main(String[] args) throws IOException {
		TomlMapper mapper = new TomlMapper();
		
		Employee emp = new Employee();
		emp.setId(1);
		emp.setFirstName("Rama Devi");
		emp.setLastName("G");
		
		String toml = mapper.writeValueAsString(emp);
		System.out.println(toml);
		
	}

}

Output

id = 1
firstName = 'Rama Devi'
lastName = 'G'

Dependency used

<dependencies>
  <dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-toml</artifactId>
    <version>2.13.4</version>
  </dependency>

  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.4</version>
  </dependency>

  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.13.4</version>
  </dependency>

  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.13.4</version>
  </dependency>

</dependencies>


 

Previous                                                 Next                                                 Home

Monday, 19 September 2022

TOML tutorial

 

      Introduction to TOML
      Key value pairs in TOML
      Add comments to TOML document
      Quick guide to keys in TOML
      Quick guide to strings in TOML
      Working with Integer data in TOML
      Working with Float data in TOML
      Boolean values in TOML
      Offset Date-Time in TOML
      Local Date time in TOML
      Local Date in TOML
      Local time in TOML
      Working with Arrays in TOML
      Working with tables in TOML
      Working with inline tables in TOML
      Working with array of tables in TOML
      Jackson: Get TOML from Java object
      Jackson: Get Java object from TOML
      Jackson: Parse TOML string in Java
      Jackson: Convert TOML to a map in java
 
Previous                                                 Next                                                 Home

Thursday, 18 August 2022

Java: convert byte[] to object and object to byte[]

Following snippet convert serializable object to byte array.

public static byte[] serialize(Serializable serializable) {

    try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
        objectOutputStream.writeObject(serializable);
        objectOutputStream.flush();
        return byteArrayOutputStream.toByteArray();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

 

Following snippet convert the byte array to object.

public static Object deserialize(byte[] byteArray) {
    try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) {
        return objectInputStream.readObject();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

 

Find the below working application.

 


User.java

 

package com.sample.app.dto;

import java.io.Serializable;

public class User implements Serializable {

    private static final long serialVersionUID = 198623L;

    private int id;

    private String name;

    public User(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 "User [id=" + id + ", name=" + name + "]";
    }

}

SerializationDemo.java

package com.sample.app;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import com.sample.app.dto.User;

public class SerializationDemo {

    public static byte[] serialize(Serializable serializable) {

        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
            objectOutputStream.writeObject(serializable);
            objectOutputStream.flush();
            return byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public static Object deserialize(byte[] byteArray) {
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
                ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) {
            return objectInputStream.readObject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public static void main(String[] args) {

        byte[] byteArr = serialize(new User(1, "Krishna"));
        User user = (User) deserialize(byteArr);

        System.out.println("Byte array representaion of user object :");
        for (byte b : byteArr) {
            System.out.print(b + " ");
        }

        System.out.println("\n\nDeserialized version of user object from byte array : ");
        System.out.println("user : " + user);
    }

}

Output

Byte array representaion of user object :
-84 -19 0 5 115 114 0 23 99 111 109 46 115 97 109 112 108 101 46 97 112 112 46 100 116 111 46 85 115 101 114 0 0 0 0 0 3 7 -33 2 0 2 73 0 2 105 100 76 0 4 110 97 109 101 116 0 18 76 106 97 118 97 47 108 97 110 103 47 83 116 114 105 110 103 59 120 112 0 0 0 1 116 0 7 75 114 105 115 104 110 97 

Deserialized version of user object from byte array : 
user : User [id=1, name=Krishna]


You may like

Java: Convert byte array to object

It is pretty simple with serialization. Just read the Serializable object from ObjectInputStream.

ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
Serializable serializable = objectInputStream.readObject();

 

Find the below working application.

 


User.java
package com.sample.app.dto;

import java.io.Serializable;

public class User implements Serializable {

    private static final long serialVersionUID = 198623L;

    private int id;

    private String name;

    public User(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 "User [id=" + id + ", name=" + name + "]";
    }

}

SerializationDemo.java

package com.sample.app;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import com.sample.app.dto.User;

public class SerializationDemo {

    public static byte[] serialize(Serializable serializable) {

        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
            objectOutputStream.writeObject(serializable);
            objectOutputStream.flush();
            return byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public static Object deserialize(byte[] byteArray) {
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
                ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) {
            return objectInputStream.readObject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public static void main(String[] args) {

        byte[] byteArr = serialize(new User(1, "Krishna"));
        User user = (User) deserialize(byteArr);

        System.out.println("Byte array representaion of user object :");
        for (byte b : byteArr) {
            System.out.print(b + " ");
        }

        System.out.println("\n\nDeserialized version of user object from byte array : ");
        System.out.println("user : " + user);
    }

}

Output

Byte array representaion of user object :
-84 -19 0 5 115 114 0 23 99 111 109 46 115 97 109 112 108 101 46 97 112 112 46 100 116 111 46 85 115 101 114 0 0 0 0 0 3 7 -33 2 0 2 73 0 2 105 100 76 0 4 110 97 109 101 116 0 18 76 106 97 118 97 47 108 97 110 103 47 83 116 114 105 110 103 59 120 112 0 0 0 1 116 0 7 75 114 105 115 104 110 97 

Deserialized version of user object from byte array : 
user : User [id=1, name=Krishna]


You may like

How to convert an object to byte array in java?

Step 1: Make the class serializable by implementing Serializable interface.

public class User implements Serializable {
    .......
    .......
}

 

Step 2: Write the Serializable object to ObjectOutputStream, make sure that ObjectOutputStream is internally using ByteArrayOutputStream.

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(serializable);
objectOutputStream.flush();

 

Step 3: Get the byte array from ByteArrayOutputStream.

byte[] byteArr = byteArrayOutputStream.toByteArray();

 

Find the below working application.

 

User.java

 

package com.sample.app.dto;

import java.io.Serializable;

public class User implements Serializable {

    private static final long serialVersionUID = 198623L;

    private int id;

    private String name;

    public User(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 "User [id=" + id + ", name=" + name + "]";
    }

}

 

SerializationDemo.java

package com.sample.app;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import com.sample.app.dto.User;

public class SerializationDemo {

    public static byte[] serialize(Serializable serializable) {

        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
            objectOutputStream.writeObject(serializable);
            objectOutputStream.flush();
            return byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public static Object deserialize(byte[] byteArray) {
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
                ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) {
            return objectInputStream.readObject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public static void main(String[] args) {

        byte[] byteArr = serialize(new User(1, "Krishna"));
        User user = (User) deserialize(byteArr);

        System.out.println("Byte array representaion of user object :");
        for (byte b : byteArr) {
            System.out.print(b + " ");
        }

        System.out.println("\n\nDeserialized version of user object from byte array : ");
        System.out.println("user : " + user);
    }

}

 


Output

Byte array representaion of user object :
-84 -19 0 5 115 114 0 23 99 111 109 46 115 97 109 112 108 101 46 97 112 112 46 100 116 111 46 85 115 101 114 0 0 0 0 0 3 7 -33 2 0 2 73 0 2 105 100 76 0 4 110 97 109 101 116 0 18 76 106 97 118 97 47 108 97 110 103 47 83 116 114 105 110 103 59 120 112 0 0 0 1 116 0 7 75 114 105 115 104 110 97 

Deserialized version of user object from byte array : 
user : User [id=1, name=Krishna]

 

You may like