0

Let x be a given object of primitive type, e.g. x is defined by int x; or char x; or ....etc.

Then, how to get name of class (i.e., int or char or ...etc) from x?

Motivation:

if(primitive type of x = int) then ....
if(primitive type of x = char) then ....
Hausdorff
  • 47
  • 5
  • 1
    In this case you are talking about primitives, not classes. There is no need to find out what `x` is, because if you defined it as `int x` it can only be an int. It cannot change. – f1sh Jan 10 '22 at 22:31
  • I want to get some function which returns `int` or `char` ...etc. – Hausdorff Jan 10 '22 at 22:32
  • 1
    `String getType(int x) { return "int"; }` – shmosel Jan 10 '22 at 22:34
  • 1
    That does not exist in java. The question is: can you come up with a scenario where you don't know what type a variable is (assuming it's a primitive)? – f1sh Jan 10 '22 at 22:35
  • I assume that I do not know `x` is `int` or `char` or.... – Hausdorff Jan 10 '22 at 22:38
  • 2
    Your edited answer suggests this might be an XY problem. What are you doing where you would need this capability? – WJS Jan 10 '22 at 22:56

2 Answers2

1

What you are describing are primitive types, not classes. You can do it like this.

class Foo {
    public int x;
    public char y;
}

Foo foo = new Foo();
Field[] fields = foo.getClass().getDeclaredFields();
for (Field f : fields) {
    System.out.println(f.getAnnotatedType() + " " + f.getName());
}
    

prints

int x
char y

If you just want to have a getter to return a value of a primitive field you can do this in your class.

int someVal = 10;
public int getSomeVal() {
    return someVal;
}
WJS
  • 36,363
  • 4
  • 24
  • 39
-1

This should help you get started for Java classes.

public int x

 class DoSomething (int x) { 
    ...
    }

Some relevant links:

Ankhit Sharma
  • 367
  • 1
  • 5
  • 16