Hi to all,
Hope you all will be fine. Consider this simple code. I just want to checked how you can get fields of the class or in other words what getFields() return.
This is the result of above codeCode:import java.lang.reflect.Field; public class Main { public static final String cat = "cat"; public static final String dog = "dog"; public static enum State { DEALLOCATED, ALLOCATING, ALLOCATED, READY, RECOGNIZING, DEALLOCATING, ERROR }; public String bird = "bird"; private String turtle = "Turtle"; public void printAnimalName() { System.out.println("Animal Name"); } public static void main(String[] args) { Main mainObject = new Main(); //Creating object of Main class /********************* * Fragment 1 ********************/ mainObject.comments(1); // Method that print comments in the output try { Class<?> t = Class.forName("Main"); //Class<?> t = Animal.class; Field fields[] = t.getFields(); for (int i = 0; i < fields.length; i++) { System.out.println(" " + fields[i]); } } catch (ClassNotFoundException e) { System.out.println("class not found " + e); } /********************* * Fragment 2 ********************/ mainObject.comments(2); //Class<?> t = Class.forName("Main"); Class<?> t = Main.class; Field fields[] = t.getFields(); for (int i = 0; i < fields.length; i++) { System.out.println(" " + fields[i]); } /********************* * Fragment 3 ********************/ mainObject.comments(3); try{ Class<?> s = Class.forName("java.lang.Integer"); Field IntegerFields[] = s.getFields(); for (int i = 0; i < IntegerFields.length; i++) { System.out.println(" " + IntegerFields[i]); } }catch (ClassNotFoundException e) { System.out.println("class not found " + e); } } // main() } //class Main
i want to ask in fragment 1 when i usedCode:run: /******************** * Fragment 1 *******************/ class not found java.lang.ClassNotFoundException: Main /******************** * Fragment 2 *******************/ public static final java.lang.String getfieldscheck.Main.cat public static final java.lang.String getfieldscheck.Main.dog public java.lang.String getfieldscheck.Main.bird /******************** * Fragment 3 *******************/ public static final int java.lang.Integer.MIN_VALUE public static final int java.lang.Integer.MAX_VALUE public static final java.lang.Class java.lang.Integer.TYPE public static final int java.lang.Integer.SIZE
then i got exception. But when i used in fragment 3Code:Class<?> t = Class.forName("Main");
then i got the result. Why in fragment 1 Class.forName("Main") fails?Code:Class<?> s = Class.forName("java.lang.Integer");
Thanks


Reply With Quote
Bookmarks