ArrayList of different classes using Object
in
Programming Questions
•
3 years ago
Hi List,
Something I've been wanting to do for a while is to be able to dynamically populate an ArrayList with instances of different classes and then use these class instances. For example, here I create two different classes. Each class has a method named drawClass(). I hope to be able to pull instances out of an ArrayList, no matter what the class, and run drawClass(), as long as a method with that name exists in the class:
- ArrayList test;
- ArrayList classes;
- void setup() {
- size(500,500);
- test = new ArrayList();
- test.add(new HLine(100.0, 5));
- test.add(new testEllipse());
- }
- void draw() {
- background(0);
- for(int i=test.size()-1; i>=0; i--) {
- Object objectToDraw = (Object) test.get(i);
- //one thought
- objectToDraw.drawClass();
- //another
- objectToDraw.getClass() objectToDraw2 = (objectToDraw.getClass()) test.get(i);
- objectToDraw2.drawClass();
- }
- }
- }
- class HLine {
- float ypos, speed;
- HLine (float y, float s) {
- ypos = y;
- speed = s;
- }
- void drawClass() {
- ypos += speed;
- if (ypos > width) {
- ypos = 0;
- }
- stroke(255,0,0);
- line(0, ypos, width, ypos);
- }
- }
- class testEllipse {
- void drawClass() {
- fill(0,0,255);
- ellipse( 200,200,100,100);
- }
- }
Another related question is, is there a method in Processing/Java where you can get a list of all of the classes/class methods/class variables within a sketch? I would guess oscPlug perhaps engages something like this to automatically pass on osc commands to methods within classes.
Thanks,
Justin
1