Posts

Map class field to map

 import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class AutogeneratedClassMapper {     public static Map<String, Object> mapFieldsToMap(Object obj) throws IllegalAccessException {         Map<String, Object> fieldMap = new HashMap<>();         Class<?> clazz = obj.getClass();         Field[] fields = clazz.getDeclaredFields();         for (Field field : fields) {             field.setAccessible(true);             Object value = field.get(obj);             fieldMap.put(field.getName(), value);         }         return fieldMap;     }     // Example usage     public static void main(String[] args) throws IllegalAccessException {         AutogeneratedClass autogeneratedObject = new AutogeneratedClass();         // Set field values in the autogeneratedObject         Map<String, Object> fieldMap = mapFieldsToMap(autogeneratedObject);         System.out.println(fieldMap);     } }

Java Design pattern

 Singleton Design pattern :-  it's Creational Design Pattern as we need to have only one instance of our class for Ex:- Logger,DBConnector. SingleObject class have its constructor as private and have a static instance of itself. Code:-  public class Singleton { private static Singleton object; private Singleton() { } public static synchronized Singleton getInstance() { if (object == null) object = new Singleton(); return object; } } Eager Initialization :-  public class Singleton { private static Singleton object = new Singleton(); private Singleton() { } public static Singleton getInstance() { return object; } } Double checked Locking :-  public class Singleton { private static volatile Singleton obj = null; private Singleton() { } public static Singleton getInstance() { if (obj == null) { synchronized (Singleton.class) { if (obj == null) obj = new Singleton(); } } return obj; } } W