Monday, June 14, 2010

Get the fild value from java class during run time using reflection

Get the fild value from java class during run time using reflection.

Suppose, you have one java class that is having a lot of static value and you want that int value during run time with dynamic field name.
Like,

public class Types
{
public static final int BIT = -7;
public static final int TINYINT = -6;
public static final int SMALLINT = 5;
public static final int INTEGER = 4;
public static final int BIGINT = -5;
public static final int FLOAT = 6;
public static final int REAL = 7;
public static final int DOUBLE = 8;
public static final int NUMERIC = 2;
public static final int DECIMAL = 3;
public static final int CHAR = 1;
public static final int VARCHAR = 12;
public static final int LONGVARCHAR = -1;
public static final int DATE = 91;
public static final int TIME = 92;
public static final int TIMESTAMP = 93;
}

And you have one string that containg the "TINYINT" during run time, now you have to fetch what is the value of TINYINT dynamically.
string filed = "TINYINT";

String field = "TINYINT";
Class typeClass = Class.forName("java.sql.Types");
int fieldValue = (Integer) typeClass.getField(field).get(null);
System.out.println("fieldValue :: "+fieldValue);


Output:

fieldValue :: -6

1 comment:

  1. Thanks for the information about Blogspot very informative for everyonefullstack python classes in pune

    ReplyDelete