-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

9
  • 4
    Class.forName() returns a Class object, not an instance of that class. Commented Oct 7, 2016 at 14:04
  • 1
    Doesn't even compile.. Commented Oct 7, 2016 at 14:05
  • 1
    Then you want a Class<Item> not a Item Commented Oct 7, 2016 at 14:05
  • 2
    And you won't be able to call the test method like that, you'll have to use Reflection. Commented Oct 7, 2016 at 14:06
  • 1
    Jesus whats up with people and the down votes. This is not a bad question at all. Actually its pretty much of something to keep in mind and learn about i will love for the proper answer so that i can implement this next time! Commented Oct 7, 2016 at 14:41

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

7 Comments

He can't call Item.test() since he receive Item into a String.. he need reflexion to get the methods (test) from the Class
In his sample code he use Item. Of course his code doesn't have sense, but I work with what I have.
I added reflection code for completeness.
It is a duplicated question ... no need for an answer ;)
It is poorly stated question :)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.