Diesal11
Diesal11

Reputation: 3417

use variable type to define another variable type

Im trying to use the type of one variable to define the type on another I know i could just put all the types in an enum then use ordinal with a switch/case to select but i'm wondering if theres an easier way.

Heres a small example:

public void loadRotation(TetrominoType type) {
TetrominoType new = new type.class();
}

TetroiminoType type = new RedTetro();
this.loadRotation(type);

RedTetro obviously extends TetrminoType

I know this won't work but hopefully from it you understand what i'm trying to do.

Upvotes: 0

Views: 104

Answers (4)

user207421
user207421

Reputation: 310850

You need to look up the Factory design pattern.

Upvotes: 0

Brian Roach
Brian Roach

Reputation: 76888

Reflection is the answer.

If you're talking about a class that has a zero argument constructor, it's quite straight forward:

MyClass c = new MyClass();
MyClass c2 = c.getClass().newInstance();

If you need to use a constructor that takes arguments you have to extract the Constructor you need and use that. Oracle provides a tutorial here:

http://download.oracle.com/javase/tutorial/reflect/member/ctorInstance.html

Upvotes: 1

redache
redache

Reputation: 21

You can use Java reflection to rewrite the type based on the type of the variable you have.

You can find out more here http://java.sun.com/developer/technicalArticles/ALT/Reflection/ and a similar problem here Dynamic variables with given type

It should be a case of utilising the base class of your type too set a basic type and then using reflection to create the variable with the new type.

Upvotes: 1

mgm8870
mgm8870

Reputation: 679

you could use the instanceof evaluator:

public class MainClass {
  public static void main(String[] a) {

    String s = "Hello";
    if (s instanceof java.lang.String) {
      System.out.println("is a String");
    }
}
}

Upvotes: 1

Related Questions