Monday 23 October 2017

What is Java Reflection API | Java Reflection | Reflection in java


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

Click the below Image to Enlarge
What is Java Reflection API | Java Reflection | Reflection in java
Student.java
public class Student
{
    private String name;
    private int age;

    public Student(String name, int age)
    {
        super();
        this.name = name;
        this.age = age;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public int getAge()
    {
        return age;
    }

    public void setAge(int age)
    {
        this.age = age;
    }

}
ReflectionDemo.java
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectionDemo
{
    public static void main(String[] args)
    {
        Student student = new Student("Peter", 25);

        /*
         * Returns: The Class object that represents the runtime class
         * of this object.
         * 
         */
        Class<? extends Student> studentClass = student.getClass();

        /*
         * Returns: the array of Method objects representing the
         * public methods of this class
         */
        Method[] methodArray = studentClass.getMethods();

        for (Method method : methodArray)
        {
            System.out.println(method.getName());
        }

        System.out.println("----------------------------------");

        /*
         * Returns:the array of Field objects representing all the
         * declared fields of this class
         */
        Field[] fieldArray = studentClass.getDeclaredFields();

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

    }

}
Output
getName
setName
getAge
setAge
wait
wait
wait
equals
toString
hashCode
getClass
notify
notifyAll
----------------------------------
name
age

Refer:
https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html

https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/package-summary.html

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

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

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/921a65d57c0ec8a07d5edae78f1552619b89e108/BasicJava/ReflectionDemo_Intro/?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
  • No comments:

    Post a Comment