R Syed
R Syed

Reputation: 1093

Calling the class in java, using the name of a class from a string

Is there any easy way to achieve this.

Let's say I have an array of string with the name of POJO's in there and I"m trying to print all the list of attributes, is there any way to achieve this easily?\

String [] nameofClass;
for(String name:nameofClass)
name.class.getDeclaredFields();

Thanks

Upvotes: 2

Views: 124

Answers (2)

Vishal K
Vishal K

Reputation: 13066

Yes you can. See the example given below:

        String [] nameofClass = {"java.lang.Object","java.lang.Thread"};//Give complete path of the class
        try{
            for(String name : nameofClass)
            {
                Class cl = Class.forName(name);
                System.out.println(cl);
                System.out.println("\t"+java.util.Arrays.toString(cl.getDeclaredFields()));
            }
        }catch(Exception ex){System.out.println(ex);}   

Upvotes: 0

sp00m
sp00m

Reputation: 48837

Class.forName(name).getDeclaredFields() within your for loop is probably what you're looking for.

Note that name should be the full path of the class, i.e. not only TheClass but the.package.to.TheClass.

Upvotes: 9

Related Questions