-2
class Item
{
    public static test()
    {
    }
}

String s = "package.Item";
Item o = (Item)Class.forName(s).cast(Item.class); // *
o.test();

but the marked line fails:

java.lang.ClassCastException: Cannot cast java.lang.Class to items.Item

Jens
  • 67,715
  • 15
  • 98
  • 113
John Smith
  • 6,129
  • 12
  • 68
  • 123

1 Answers1

1

To create new instance you need to do the following

Class c = Class.forName("Item");
Item i = (Item)c.newInstance();

If you want to invoke static method you just call it on class instead of instance

Item.test();

Or you can use reflection without directly reference to class

Class c = Class.forName("Item");
Method method = c.getMethod("test");
method.invoke(null);
talex
  • 17,973
  • 3
  • 29
  • 66
  • 1
    He can't call Item.test() since he receive Item into a String.. he need reflexion to get the methods (test) from the Class – AxelH Oct 07 '16 at 14:09
  • 1
    In his sample code he use `Item`. Of course his code doesn't have sense, but I work with what I have. – talex Oct 07 '16 at 14:11
  • It's in the title `how to convert a string to class and call its static method?` Item that he tried to create from the String ;) – AxelH Oct 07 '16 at 14:12
  • 1
    I added reflection code for completeness. – talex Oct 07 '16 at 14:15
  • 1
    It is a duplicated question ... no need for an answer ;) – AxelH Oct 07 '16 at 14:18
  • 1
    It is poorly stated question :) – talex Oct 07 '16 at 14:20
  • yes, there was a need for an answer... I coulnt know that I need this line too: "Method method = c.getMethod("test");", I thought somehow c.test can be invoked, by casting – John Smith Oct 07 '16 at 14:27