简体   繁体   English

在 Java 中是否有数据类型的数据类型?

[英]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;编辑:所以当我提到数据类型时,我指的是声明变量之前的部分,例如: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我想传递类型,因此该方法可以采用 string 或 int 并将其识别为数据类型而不是字符串,而不是为每个原始数据类型使用 switch case

I will use the method to keep validating inputs, instead of try, except我将使用该方法来不断验证输入,而不是尝试,除了

Basically, I'm asking what the following underscore is:基本上,我问的是以下下划线是什么:

_____ variable1 = String; _____ 变量 1 = 字符串;

variable1 variable2 = “Words”;变量 1 变量 2 = “单词”;

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如果有一种方法可以使用扫描仪而不是指定数据类型来获取通用输入,或者使用 variable1 指定数据类型

您正在寻找java.lang.Class

I have in mind three solution for your problem, because I don't know exactly what you want.对于您的问题,我想到了三种解决方案,因为我不确切知道您想要什么。

1.Object 1.对象

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).但是,使用它,您将无法使用您在类中编写的个人方法(只是覆盖特定于 Object 类的方法)。

2.Class 2.班级

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)正如 Mureinik 已经回答的那样,java.lang.Class 是一个对象,它包含运行时有关您的类的信息,这意味着您可以获得例如类的名称和其他有用的东西(查看文档)

3.Generics 3.泛型

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 )通过泛型类,您可以创建适用于不同类型对象的不同方法(例如,从Number扩展的方法)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM