15

I want to print all the class names in a package and also to print the corresponding attributes and their data types in each package.

In one code, I am able to get the classnames in the form of string. In another code I am able to get the attributes and their data types using Classname.class.getAttribute();

However I want to merge the two codes. Since in the first code I got the classnames in the form of string , I can't use Classname.class.getAttribute() since here Classname will be of type String.

So I want a method which will convert the "Classname" from String type to Class type.

I tried Class.forName() but it didn't work.

3
  • 6
    Please specify how Class.forName() "didn't work." Commented Sep 5, 2012 at 17:39
  • 3
    If Class.forName() didn't work, its very likely that a) the class name is not right b) you got an error message but didn't know what it meant so you ignored it. ;) Commented Sep 5, 2012 at 17:40
  • 1
    Post your error message! and post the code where you tried using Class.forName() Commented Sep 5, 2012 at 17:44

3 Answers 3

27
Class<?> classType = Class.forName(className);

Make sure className is fully qualified class name like com.package.class Also, please share your error message that you see.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, the className was not fully qualified. Upon giving the fully qualified name, it worked :) Thanks :)
1

If the fully-qualified name of a class is available, it is possible to get the corresponding Class using the static method Class.forName().

Eg:

Class c = Class.forName("com.duke.MyLocaleServiceProvider"); 

Note: Make sure the parameter you provide for the function is fully qualified class name like com.package.class

Check here for any reference.

EDIT:

You could also try using loadClass() method.

Eg:

 ClassLoader cl;
 Class c = cl.loadClass(name);

It is invoked by the Java virtual machine to resolve class references.

Syntax:

public Class<?> loadClass(String name)
                   throws ClassNotFoundException

For details on ClassLoader check here

Here is an implementation of ClassLoader.

Comments

1

Please try as following.

String str = "RequiredClassName";    
Class <?> Cref = Class .forName("PackageNaem."+str );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.