Java-Gaming.org
Play Revenge of the Titans! The situation is critical. We need fancy commanders to defend Earth, the moon, Mars!
Featured games (78)
games approved by the League of Dukes
Games in Showcase (406)
games submitted by our members
Games in WIP (289)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Making an object for a class based on a variable (is it even possible?)  (Read 1211 times)
0 Members and 1 Guest are viewing this topic.
Offline h3ckboy
« Posted 2011-08-14 14:48:15 »

Hey, sorry if this doesnt make much sense, but I cannot explain it very well.

so is it possible, and if so how, to make an object based on a variable. so for example. I have a string and the string is currently "Foo" is there a way to then make "new Foo foo;" based on that?

but of course I cant just do "new Foo foo;" The class has to be whatever the string is.

Sorry if this makes absolutely no sense, or if I am going about this the wrong way.
Offline Riven
« League of Dukes »

JGO Overlord


Medals: 437
Projects: 4


Hand over your head.


« Reply #1 - Posted 2011-08-14 14:50:48 »

1  
Object fooInstance = Class.forName(fooString).newInstance();

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Projects: Revenge of the Titans, Titan Attacks, Droid Assault, and Ultratron
Offline Cero
« Reply #2 - Posted 2011-08-14 14:54:29 »

I kinda get it, but obviously the question would be "why ?"
apart from that:  if the fields of the new object have names, according to some string values... you couldn't even use the new object / its fields, because at compile time there would be no fields / you wouldnt know its names yet - so you couldnt use it

sounds like dynamically named variables... I don't know

but obviously what you really could do is to have a class with a hashmap, and then use that

Games published by our own members! Check 'em out!
Try the Free Demo of Revenge of the Titans
Offline CaptainJester

JGO Knight


Medals: 10
Projects: 2


Make it work; make it better.


« Reply #3 - Posted 2011-08-14 14:56:28 »

Reflection will do it. Keep in mind that invoking methods with Reflection is slow. But if you create all your class in a place where speed doesn't matter then call the methods from a variable or stored collection the speed is normal.
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
public interface Shape {
  public void draw();
}
public class Triangle implements Shape {
  public void draw() {
    ...
  }
}
public class Square implements Shape {
  public void draw() {
    ...
  }
}
public class Program {
  ArrayList<Shape> shapes = new ArrayList<Shape>();
  public static void main(String args[]) {
    ArrayList<String> names = //load all your strings here
   for(String name:names) {
      //exceptions left out for brevity
     //invoke constructor method is slow
     shapes.add(Class.forName(name).newInstance());
    }
    for(Shape shape:shapes) {
      //since this part invokes the draw method without reflection the speed is normal
     shape.draw();
    }
  }
}

Offline h3ckboy
« Reply #4 - Posted 2011-08-14 15:16:09 »

I think that rivens method is exactly what I am looking for, thanks!

as for the why, it is because I need to make a new object to be added to a list, and which class it is is based on that string.
Offline Riven
« League of Dukes »

JGO Overlord


Medals: 437
Projects: 4


Hand over your head.


« Reply #5 - Posted 2011-08-14 15:20:26 »

I kinda get it, but obviously the question would be "why ?"
apart from that:  if the fields of the new object have names, according to some string values...
It's very useful for loading implementations of interfaces

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Projects: Revenge of the Titans, Titan Attacks, Droid Assault, and Ultratron
Offline Roquen

JGO Ninja


Medals: 66



« Reply #6 - Posted 2011-08-14 15:30:39 »

Scripting interfacing and/or hot deployment are a couple of examples.
Offline h3ckboy
« Reply #7 - Posted 2011-08-14 15:52:02 »

Hey, I tried rivens way, and I got an error saying that the class did not exist, when I am certain it does, so ist here any special things I have to have in the string like .class or soemthing?
Offline Riven
« League of Dukes »

JGO Overlord


Medals: 437
Projects: 4


Hand over your head.


« Reply #8 - Posted 2011-08-14 16:02:21 »

google FQCN

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Projects: Revenge of the Titans, Titan Attacks, Droid Assault, and Ultratron
Offline Orangy Tang

JGO Kernel


Medals: 48
Projects: 11


Monkey for a head


« Reply #9 - Posted 2011-08-14 17:20:05 »

Hey, I tried rivens way, and I got an error saying that the class did not exist, when I am certain it does, so ist here any special things I have to have in the string like .class or soemthing?
You need the full class name (ie. with the package as well). So something like "java.util.ArrayList", not just "ArrayList".

[ TriangularPixels.com - Play Growth Spurt, Rescue Squad and Snowman Village ] [ Rebirth - game resource library ]
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline h3ckboy
« Reply #10 - Posted 2011-08-14 17:20:53 »

I tried that too, and it didnt work right. maybe i messed something up, I'll give it another look.

EDIT:

Turns out I had the class name right, but I was just getting a different error, java.lang.InstantiationException.

a quick google says that it is caused when the class is an interface or an abstract, which my class is not Tongue. any thoughts?

thanks
Offline Riven
« League of Dukes »

JGO Overlord


Medals: 437
Projects: 4


Hand over your head.


« Reply #11 - Posted 2011-08-14 17:31:13 »

If your class has a non-default constructor, you need:

1  
Class.forName(fqcn).getConstructor(...).newInstance(...)

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Projects: Revenge of the Titans, Titan Attacks, Droid Assault, and Ultratron
Offline h3ckboy
« Reply #12 - Posted 2011-08-14 17:39:50 »

oh, so if it extends something like mine does?

I'll try that, thanks Smiley
Offline Riven
« League of Dukes »

JGO Overlord


Medals: 437
Projects: 4


Hand over your head.


« Reply #13 - Posted 2011-08-14 17:44:17 »

well, whether it extends something has nothing to do with it. just read the javadoc, and google a bit, if it's not clear.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Projects: Revenge of the Titans, Titan Attacks, Droid Assault, and Ultratron
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

Play Revenge of the Titans! The situation is critical. We need fancy commanders to defend Earth, the moon, Mars!
 
Get high quality music tracks for your game!

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

The invasion has landed! On Mars! And you're there to beat 'em!
cubemaster21 (60 views)
2013-05-17 21:29:12

alaslipknot (69 views)
2013-05-16 21:24:48

gouessej (99 views)
2013-05-16 00:53:38

gouessej (96 views)
2013-05-16 00:17:58

theagentd (107 views)
2013-05-15 15:01:13

theagentd (98 views)
2013-05-15 15:00:54

StreetDoggy (144 views)
2013-05-14 15:56:26

kutucuk (167 views)
2013-05-12 17:10:36

kutucuk (166 views)
2013-05-12 15:36:09

UnluckyDevil (175 views)
2013-05-12 05:09:57
Complex number cookbook
by Roquen
2013-04-24 12:47:31

2D Dynamic Lighting
by Oskuro
2013-04-17 16:46:12

2D Dynamic Lighting
by Oskuro
2013-04-17 16:45:57

2D Dynamic Lighting
by Oskuro
2013-04-17 16:23:20

Noise (bandpassed white)
by Roquen
2013-04-05 17:36:01

Noise (bandpassed white)
by Roquen
2013-04-03 16:17:38

Java Data structures
by Roquen
2013-03-29 13:21:12

Topic Request
by kutucuk
2013-03-22 21:42:01
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!
Page created in 0.114 seconds with 22 queries.