Creating new instance Creating new instance using Reflection technique means You would call the contructor of the class. First of all, you gotta set the parameters for the constructor.
Create Class<?> by Class name 1 Class<T> clazz = (Class<T>) Class.forName("CLASSNAME" );
You could do either like this.
Setting Parameters 1 Class[] classArgs = {Map.class, Map.class};
Setting Contruction method 1 Constructor constructor = clazz.getDeclaredConstructor(classArgs);
Create new instance 1 Object obj = constructor.newInstance(map1, map2);
Access All fields 1 2 3 4 5 6 7 8 Field[] fields = object.getClass().getDeclaredFields(); for (Field field : fields) { field.getName(); field.getType(); }
Getter/Setter Invoke 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 private void callSetter (Object obj, String fieldName, Object value) { PropertyDescriptor pd; try { pd = new PropertyDescriptor (fieldName, obj.getClass()); pd.getWriteMethod().invoke(obj, value); } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); } } private void callGetter (Object obj, String fieldName) { PropertyDescriptor pd; try { pd = new PropertyDescriptor (fieldName, obj.getClass()); System.out.println("" + pd.getReadMethod().invoke(obj)); } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); } } public static void main (String[] args) { GetterAndSetter gs = new GetterAndSetter (); TestClass tc = new TestClass (); gs.callSetter(tc, "name" , "John" ); gs.callSetter(tc, "value" , 12 ); gs.callSetter(tc, "flag" , true ); Field[] fields = tc.getClass().getDeclaredFields(); for (Field f : fields){ String fieldName = f.getName(); System.out.println("Field Name -- " + fieldName); } gs.callGetter(tc, "name" ); gs.callGetter(tc, "value" ); gs.callGetter(tc, "flag" ); }
They are offered from PropertyDescriptor object. But i think it’s too restrict. so You can invoke just a getter method via the getter name.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 private static <T> String getter (T t, String fieldName) { try { String getterMethodName = "get" + fieldName.substring(0 , 1 ).toUpperCase() + fieldName.substring(1 ); Method method = t.getClass().getDeclaredMethod(getterMethodName); return String.valueOf(method.invoke(t)); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { log.info(e.toString()); e.printStackTrace(); return "" ; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 @SuppressWarnings("unchecked") public static <T, U> List<T> map (List<U> srcs, String fieldName, Class<T> clazz) throws NoSuchFieldException, IllegalAccessException { List<T> res = new ArrayList <>(); for (U src : srcs) { Field field = src.getClass().getDeclaredField(fieldName); field.setAccessible(true ); res.add((T) field.get(src)); } return res; }