Friday, 18 March 2022

Java: Get the field data type using reflection

'java.lang.reflect.Field' class provides getType method, which returns a Class object that identifies the declared type for the field represented by this Field object.

 

Signature

public Class<?> getType()

 

Example

Class clazz = field.getType();

 

 


Find the below working application.

 

ChatServer.java

 

package com.sample.app;

public class ChatServer {

	@Deprecated
	private int connectionTimeout;
	private int bufferSize;

	public ChatServer(int connectionTimeout, int bufferSize) {
		this.connectionTimeout = connectionTimeout;
		this.bufferSize = bufferSize;
	}

	public int getConnectionTimeout() {
		return connectionTimeout;
	}

	public void setConnectionTimeout(int connectionTimeout) {
		this.connectionTimeout = connectionTimeout;
	}

	public int getBufferSize() {
		return bufferSize;
	}

	public void setBufferSize(int bufferSize) {
		this.bufferSize = bufferSize;
	}

}

GetFieldType.java

package com.sample.app;

import java.lang.reflect.Field;

public class GetFieldType {
	
	public static void main(String[] args) {
		ChatServer chatServer = new ChatServer(10000, 25000);
		
		Field[] fields = chatServer.getClass().getDeclaredFields();
		for(Field field: fields) {
			Class<?> clazz = field.getType();
			
			System.out.println(field.getName() + " is defined with type " + clazz.getSimpleName());
			
		}
		
	}

}

Output

connectionTimeout is defined with type int
bufferSize is defined with type int







Previous                                                    Next                                                    Home

No comments:

Post a Comment