• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to instanciate a class by name?

 
Vinicius Souza
Ranch Hand
Posts: 70
1
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need tp intanciate a class using only a string. Its possibel to do it?
 
Jeanne Boyarsky
author & internet detective
Sheriff
Posts: 36032
432
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Class c = Class.forName("nameOfClass");
c.newInstance();
 
Vinicius Souza
Ranch Hand
Posts: 70
1
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jeanne Boyarsky wrote:Class c = Class.forName("nameOfClass");
c.newInstance();

Thanks a lot! Its solved my problem
Best regards,
Vinicius
 
Vinicius Souza
Ranch Hand
Posts: 70
1
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jeanne, its means that, the class have to be an empty constructor ? And if not, its will trows an exception?
Thanks in advance!
 
Darryl Burke
Bartender
Posts: 5162
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think we need some context here. What are you trying to achieve? (Note: Not how you're trying to do it, we already have some idea of that.)
 
my overalls have superpowers - they repel people who think fashion is important. Tiny ad:
the new thread boost feature brings a LOT of attention to your favorite threads
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!