Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

creating object using newInstance() method  RSS feed

 
sekhar soma
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have a class as shown below

class A

{
public void display()
{
System.out.println("In display() method of A");

}
}

I created the object for this class in the below class as shown below

class B
{
public static void main(String args[])
{
Class c=Class.forName("A");
Object o=c.newInstance();

}
}

The above code workd fine without any errors.But when i tried to access the display() method of A like o.display(),it is displaying a compile error saying "cannot resolve symbol";

what i have to do if i want to access the display() method of A using the object created as showm above in class B.

regards,
Thanks in Advance,
Sekhar Soma
 
pascal betz
Ranch Hand
Posts: 547
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you reference the instance of A as Object therefore you need to cast it:


then you can use all the methods that are defined in A.



p
 
Jass Singh
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Object o=c.newInstance();

As pascal said, though the above line creates an instance of A but it referenced as Object, so you can invoke only methods which are defined on Object class and not the ones defined in A class.

However is A overrides some method of Object (say toString()) then you will see A's version of that method being called.




Here output will be: In toString() method of A
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by pascal betz:
you reference the instance of A as Object therefore you need to cast it:


then you can use all the methods that are defined in A.


Pascal's advice, why not syntactically incorrect, is of questionable value. Why write:

Class c=Class.forName("A");
A a = (A) c.newInstance();

When you can write

A a = new A();

Let me suggest two more useful ways to use newInstance:

1. Assume you know a subclass of the named class, or an interface that it implements. Then you can cast to that type and invoke that type's methods.

2. Use java.lang.reflect.Method to invoke a method given its name (and perhaps its argument types).

Both these approaches are commonly used when working with application configuration files.

Demo:
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!