Friday, 27 October 2017

How to access the fields of a class using Java Reflection | Reflection in java


Click here to watch in Youtube :
https://www.youtube.com/watch?v=cYUWoR8X5IM&list=UUhwKlOVR041tngjerWxVccw

Student.java
class Student
{
    public String name;
    public String age;
    
    public void showMessage()
    {
        System.out.println("Hi");
    }
}
ReflectionDemo.java
import java.lang.reflect.Field;

/**
 *
 * We can access the fields (member variables) of a class.
 *
 */
public class ReflectionDemo
{
    public static void main(String[] args)
    {

        Class<Student> classObj = Student.class;

        /*
         * Returns:the array of Field objects representing the public fields.
         */

        Field[] fieldArray = classObj.getFields();

        for (Field field : fieldArray)
        {
            System.out.println(field);
            System.out.println(field.getName());
            System.out.println("---------------------------------");
        }

    }

}
Output
public java.lang.String Student.name
name
---------------------------------
public java.lang.String Student.age
age
---------------------------------

Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/ReflectionDemo_access_fields.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/ReflectionDemo_access_fields

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/6c95796df09abfb09587d07613e2e6d5f9ad024e/BasicJava/ReflectionDemo_access_fields/?at=master

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • 1 comment:

    1. Very Interesting topic and usefull for every One and if you wants to learn some Core Java Interview Questions

      ReplyDelete