开发者

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 load开发者_StackOverflowRotation(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.


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


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");
    }
}
}


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.


You need to look up the Factory design pattern.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜