Llione
Llione

Reputation: 49

In Java is there a data types for data types?

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

Edit: 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

Upvotes: 1

Views: 101

Answers (2)

Cipri
Cipri

Reputation: 69

I have in mind three solution for your problem, because I don't know exactly what you want.

1.Object

This is the data type that can accept and sustain any data type(that is an instance of a class). However, using this, you won't be able to use your personal methods written in your class(just overriding ones that are specific to Object class).

2.Class

As Mureinik already answered, java.lang.Class is an Object that contains information about your class at run-time, meaning that you can get for example the name of your class and others useful things(look in documentation)

3.Generics

Want to create a Class that supports different kind of object? Generics are your solution. Via generic classes, you can create different methods that will work for different kind of object(for example, the ones extended from Number)

Upvotes: 2

Mureinik
Mureinik

Reputation: 311228

You're looking for java.lang.Class.

Upvotes: 5

Related Questions