0

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.

1
  • Assuming an object is passed, see the Object.getClass() method and follow the links from there -- which would allow reflection utilization. Other options include passing in a Class<...> or using a "factory pattern". Commented Oct 17, 2011 at 1:11

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

But theres 7 different types, i was trying to avoid writing a condition statement for each class
This also doesn't really answer the fundamental question: how to pass a type-constructor to a method?
1

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.

Comments

0

You need to look up the Factory design pattern.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.