1

I would like to pass a data type into a method but I can’t seem to find a data type for data types, I’m not sure what to do

So when I refer to data type I refer to the part before declaring a variable, for example: int myNumber;

I would like to pass the type, so the method could take string or int and recognise it as the data type rather than a string, instead of using switch cases for each primitive data type

I will use the method to keep validating inputs, instead of try, except

Basically, I’m asking what the following underscore is:

_____ variable1 = String;

variable1 variable2 = “Words”;

And if there is a way to take a generic input using a scanner rather than specifying a data type, or to specify the data type using variable1

0

1 Answer 1

2

I suspect you want the reflection type:
java.lang.reflect.Type you can use it in the following way:

Type type = Integer.class;

or in a method signature like:

  public void test(Type type) {

which you could then call like:

test(Integer.class)

For this to work, you would need to be using non-primitive classes, so for int, you would use the class Integer. String is fine, as that's not primitive.
If you need to check that a variable instance is of a particular type, you can use the instanceof keyword, like so:

    if (type == String.class && parameterVariable instanceof String) {
      stringField = parameterVariable;
    }

(You may have passed parameterVariable to the method as an Object, so it could be Integer or String for example). Unfortunately, the declaration pattern you are suggesting is I think unsupported in java (happy to be corrected).

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

1 Comment

I suspect there are better ways to do this than reflection. Generics, delegation, and wrapper classes come to mind. But it’s hard to say without knowing more about what Llione is really trying to achieve.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.