is there any method or class for getting the datatype of a variable????

After the variable is declared i must get the datatype......
hw can i do ....
any ideas??

Recommended Answers

All 3 Replies

Assuming that I understood correctly and you need to know the type of your variable.

Then if it is an Object try this:

String obj = "asd";

        System.out.println(obj);
        System.out.println(obj.getClass());
        System.out.println(obj.getClass().getName());

It will print:

asd
class java.lang.String
java.lang.String

If it is a primitive type, I have tried this and it worked. It converts the primitive type to its object type:

int i = 0;
        Object obj = i;

        System.out.println(obj);
        System.out.println(obj.getClass());
        System.out.println(obj.getClass().getName());

It prints:

0
class java.lang.Integer
java.lang.Integer

If this doesn't cover you, give more details

is there any method or class for getting the datatype of a variable????

After the variable is declared i must get the datatype......
hw can i do ....
any ideas??

You can get the type of any member variable or local reference type variables using reflection; for local primitive variables, AFAIK, you can't get the type.

import java.lang.reflect.*;

public class Test {

  private int i;

  private String s;

  public static void main(final String[] args) {
    for(Field f : Test.class.getDeclaredFields()) {
      System.out.println(f.getName() + " -> " + f.getType());      
    }
    String s = "test";
    System.out.println("test: " + s.getClass());
  }

}

Maybe shedding a bit of light on what you are trying to achieve here would help us coming with more to the point suggestions.

thnk u guys thnk u very much ........
it helped me ...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.