Vitaly Menchikovsky
Vitaly Menchikovsky

Reputation: 8884

how to convert string to class name

I am trying to convert string to class name. My code is:

app.actNum = "third.class";
        in.close();
                //on test
                   //  Intent intent = new Intent(this.context,Class.forName(app.actNum));



Intent dialogIntent = new Intent(getBaseContext(), Class.forName(app.actNum));

but get

  get ClassNotFoundException on Class.forName android

Upvotes: 4

Views: 15687

Answers (2)

Zakaria
Zakaria

Reputation: 15070

I think you have some problems with the path.

First, try and get the complete path :

String completePath = PathForClass.class.getResource(app.actNum).toString();

Then, all you have to do is to invoke it as you did:

 Class.forName(completePath.replace(".class","")

(As stated in the other answers, you have to remove the .class. )

Upvotes: 0

Adel Boutros
Adel Boutros

Reputation: 10285

When calling Class.forName(), you should use the class's name without the extension. So if your class is calledTest and is in the package mypackage.tests, then you should use:

Class.forName("mypackage.tests.Test")

Upvotes: 31

Related Questions