Whenever we get an object from the Collection then we have to explicitly type cast that object to the desired type. This type of conversion is unsafe as we complier did not know the type and it may fail at runtime. Generics provide a way to tell the compiler type of objects collection carries . The syntax of the generics are as follows:-


Collection <Type> obj= new <Type> Collectionclass();


The same way we can create generic methods which will accept the any type of objects and then do the processing accordingly. The utility class contains the generic method. 


The following is the example for the Generics.


package com.visualbuilder;


import java.lang.reflect.Field;


 


public class Utility {


  public static <T> void inject(Class<T> resolveeClass, T resolveeInstance) {
            Field[] fields = resolveeClass.getFields();
           if (fields != null) {
                  for (Field field : fields) {
                             if (field.getAnnotation(HelloAnnotation.class) != null) {
                                     try {
                                                field.set(resolveeInstance, "Hello, Annotation World!");
                                                } catch (IllegalAccessException e) {
                                                    e.printStackTrace();
                                                }
                                    }
                            }
                }
        }
    }

                    

Copyright © 2012 VisualBuilder. All rights reserved