Click here to watch in Youtube :
https://www.youtube.com/watch?v=k7G1WAe6syw&list=UUhwKlOVR041tngjerWxVccw
Click the below Image to Enlarge
Kids:rain rain go away little johnny wants to play | Rain Rain go away |
Kids:rain rain go away little johnny wants to play | Rain Rain go away |
class Student
{
public String name;
public int age;
}
ReflectionDemo.javaimport java.lang.reflect.Field; /** * * Getting and Setting Field Values. * */ public class ReflectionDemo { public static void main(String[] args) { try { Class<Student> classObj = Student.class; /* * Returns:the Field object of this class specified by name */ Field ageField = classObj.getField("age"); System.out.println("Field Name = " + ageField.getName()); System.out.println("Field Type = " + ageField.getType()); Student student = classObj.newInstance(); /* * Sets the field represented by this Field object on the specified * object argument to the specified new value. */ ageField.set(student, 23); Object ageValue = ageField.get(student); System.out.println("age = "+ageValue); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException | InstantiationException e) { e.printStackTrace(); } } }Output
Field Name = age Field Type = int age = 23Click the below link to download the code:
import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; /** * * Instantiating Objects using Constructor Object. * */ public class ReflectionDemo { public static void main(String[] args) { try { Class classObj = String.class; /* * Parameters: * * parameterTypes - the parameter array * * Returns: the Constructor object of the public * constructor that matches the specified parameterTypes * */ Constructor constructor = classObj.getConstructor(StringBuffer.class); StringBuffer sb = new StringBuffer("Peter"); /* * Returns:a new object created by calling the constructor * this object represents */ String str = (String) constructor.newInstance(sb); System.out.println(str); } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); } } }Output
PeterClick the below link to download the code:
import java.lang.reflect.Constructor; import java.lang.reflect.Parameter; import java.util.HashSet; /** * * We can read what parameters a given constructor can takes. * */ public class ReflectionDemo { public static void main(String[] args) { Class<HashSet> classObj = HashSet.class; /* * Returns:the array of Constructor objects representing the public * constructors of this class */ Constructor[] constructorArray= classObj.getConstructors(); for (Constructor constructor : constructorArray) { System.out.println("constructor = "+constructor); System.out.println("Parameter Count = "+constructor.getParameterCount()); /* * Returns:an array of Parameter objects representing all the * parameters to the executable this object represents. */ Parameter[] parameterArray = constructor.getParameters(); for (Parameter parameter : parameterArray) { System.out.println("Parameter Type = "+parameter.getParameterizedType()); System.out.println("Parameter Name = "+parameter.getName()); } System.out.println("--------------------------------"); } } }Output
constructor = public java.util.HashSet(int) Parameter Count = 1 Parameter Type = int Parameter Name = arg0 -------------------------------- constructor = public java.util.HashSet(int,float) Parameter Count = 2 Parameter Type = int Parameter Name = arg0 Parameter Type = float Parameter Name = arg1 -------------------------------- constructor = public java.util.HashSet(java.util.Collection) Parameter Count = 1 Parameter Type = java.util.Collection<? extends E> Parameter Name = arg0 -------------------------------- constructor = public java.util.HashSet() Parameter Count = 0 --------------------------------Click the below link to download the code:
import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Inherited @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @interface MyAnnotation { } @MyAnnotation class Display { public void showMessage() { System.out.println("Hi"); } }ReflectionDemo.java
import java.lang.annotation.Annotation; /** * * We can access the class annotations of a class. * */ public class ReflectionDemo { public static void main(String[] args) { Class<Display> classObj = Display.class; /* * Returns:annotations present on this element. */ Annotation[] annotationArray = classObj.getAnnotations(); for (Annotation annotation : annotationArray) { System.out.println(annotation); } } }Output
@MyAnnotation()Click the below link to download the code:
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:
import java.lang.reflect.Method; import java.util.ArrayList; /** * * We can access the methods of a class. * */ public class ReflectionDemo { public static void main(String[] args) { Class<ArrayList> classObj = ArrayList.class; /* * Returns:the array of Method objects representing the public methods * of this class. */ Method[] methodArray = classObj.getMethods(); for (Method method : methodArray) { System.out.println(method); } } }Output
public boolean java.util.ArrayList.add(java.lang.Object) public void java.util.ArrayList.add(int,java.lang.Object) public boolean java.util.ArrayList.remove(java.lang.Object) public java.lang.Object java.util.ArrayList.remove(int) public java.lang.Object java.util.ArrayList.get(int) public java.lang.Object java.util.ArrayList.clone() public int java.util.ArrayList.indexOf(java.lang.Object) public void java.util.ArrayList.clear() public boolean java.util.ArrayList.contains(java.lang.Object) public boolean java.util.ArrayList.isEmpty() public java.util.Iterator java.util.ArrayList.iterator() public int java.util.ArrayList.lastIndexOf(java.lang.Object) public void java.util.ArrayList.replaceAll(java.util.function.UnaryOperator) public int java.util.ArrayList.size() public java.util.List java.util.ArrayList.subList(int,int) public java.lang.Object[] java.util.ArrayList.toArray(java.lang.Object[]) public java.lang.Object[] java.util.ArrayList.toArray() public java.util.Spliterator java.util.ArrayList.spliterator() public boolean java.util.ArrayList.addAll(int,java.util.Collection) public boolean java.util.ArrayList.addAll(java.util.Collection) public void java.util.ArrayList.forEach(java.util.function.Consumer) public java.lang.Object java.util.ArrayList.set(int,java.lang.Object) public void java.util.ArrayList.ensureCapacity(int) public void java.util.ArrayList.trimToSize() public java.util.ListIterator java.util.ArrayList.listIterator() public java.util.ListIterator java.util.ArrayList.listIterator(int) public boolean java.util.ArrayList.removeAll(java.util.Collection) public boolean java.util.ArrayList.removeIf(java.util.function.Predicate) public boolean java.util.ArrayList.retainAll(java.util.Collection) public void java.util.ArrayList.sort(java.util.Comparator) public boolean java.util.AbstractList.equals(java.lang.Object) public int java.util.AbstractList.hashCode() public java.lang.String java.util.AbstractCollection.toString() public boolean java.util.AbstractCollection.containsAll(java.util.Collection) public final void java.lang.Object.wait() throws java.lang.InterruptedException public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException public final native java.lang.Class java.lang.Object.getClass() public final native void java.lang.Object.notify() public final native void java.lang.Object.notifyAll() public default java.util.stream.Stream java.util.Collection.stream() public default java.util.stream.Stream java.util.Collection.parallelStream()Click the below link to download the code:
import java.lang.reflect.Constructor; import java.util.ArrayList; /** * * We can access the constructors of a class. * */ public class ReflectionDemo { public static void main(String[] args) { Class<ArrayList> classObj = ArrayList.class; /* * Returns:the array of Constructor objects representing the public * constructors of this class */ Constructor<?>[] constructorArray = classObj.getConstructors(); for (Constructor constructor : constructorArray) { System.out.println(constructor); System.out.println("Name = "+constructor.getName()); System.out.println("ParameterCount = "+constructor.getParameterCount()); System.out.println("-----------------------------"); } } }Output
public java.util.ArrayList(java.util.Collection) Name = java.util.ArrayList ParameterCount = 1 ----------------------------- public java.util.ArrayList() Name = java.util.ArrayList ParameterCount = 0 ----------------------------- public java.util.ArrayList(int) Name = java.util.ArrayList ParameterCount = 1 -----------------------------Click the below link to download the code:
import java.util.ArrayList; /** * * It is possible to get a list of the interfaces implemented by a given class * */ public class ReflectionDemo { public static void main(String[] args) { Class<ArrayList> classObj = ArrayList.class; /* * Returns:an array of interfaces implemented by this class. * * A class can implement many interfaces. Therefore an array of Class is * returned. Interfaces are also represented by Class objects in Java * Reflection. */ Class[] classArray = classObj.getInterfaces(); for (Class class1 : classArray) { System.out.println(class1.getName()); } } }Output
java.util.List java.util.RandomAccess java.lang.Cloneable java.io.SerializableClick the below link to download the code:
import java.util.ArrayList; /** * * From the Class object we can access the superclass of the class. * */ public class ReflectionDemo { public static void main(String[] args) { Class<ArrayList> classObj = ArrayList.class; /* * Returns:the superclass of the class represented by this object. */ Class<? super ArrayList> superClass = classObj.getSuperclass(); System.out.println(superClass); System.out.println("Name = "+superClass.getName()); System.out.println("Simple Name = "+superClass.getSimpleName()); } }Output
class java.util.AbstractList
Name = java.util.AbstractList
Simple Name = AbstractList
Click the below link to download the code:import java.util.ArrayList; public class ReflectionDemo { public static void main(String[] args) { Class<ArrayList> classObj = ArrayList.class; /* * Gets the package for this class. The class loader of this class is * used to find the package. */ Package packageObj = classObj.getPackage(); /* * Returns:The fully-qualified name of this package */ System.out.println("Package Name = " + packageObj.getName()); /* * Returns:the title of the implementation, null is returned if it is not known. */ System.out.println("ImplementationTitle = "+packageObj.getImplementationTitle()); /* * Returns:the version of the implementation, null is returned if it is not known. */ System.out.println("ImplementationVersion = "+packageObj.getImplementationVersion()); /* * Returns:the specification vendor, null is returned if it is not known. */ System.out.println("SpecificationVendor = "+packageObj.getSpecificationVendor()); /* * Returns:the specification title, null is returned if it is not known. */ System.out.println("SpecificationTitle = "+packageObj.getSpecificationTitle()); } }Output
Package Name = java.util ImplementationTitle = Java Runtime Environment ImplementationVersion = 1.8.0_144 SpecificationVendor = Oracle Corporation SpecificationTitle = Java Platform API SpecificationClick the below link to download the code:
What is Java Reflection API_V2 | Java Reflection | Reflection in java |
public class Display { private void DisplayNumber(int i) { System.out.println(i); } }ReflectionDemo.java
import java.lang.reflect.Method; /** * How to call parameterized private method from another class? * * We can call the private method from outside the class by changing the runtime * behaviour of the class. * * By the help of "java.lang.Class" class and "java.lang.reflect.Method" class, * we can call private method from any other class. * */ public class ReflectionDemo { public static void main(String[] args) { try { Class<Display> classObj = Display.class; Object displayObject = classObj.newInstance(); Method method = classObj.getDeclaredMethod("DisplayNumber", new Class[] { int.class }); method.setAccessible(true); method.invoke(displayObject, 1000); } catch (Exception e) { e.printStackTrace(); } } }Output
1000
Click the below link to download the code:public class Student { private String firstName = "Peter"; private String lastName = "J"; private void showStudentFullName() { System.out.println(firstName + " " + lastName); } }ReflectionDemo.java
import java.lang.reflect.Method; /** * How to call private method from another class in java? * * We can call the private method from outside the class by changing * the runtime behaviour of the class. * * By the help of "java.lang.Class" class and * "java.lang.reflect.Method" class, we can call private method from * any other class. * */ public class ReflectionDemo { public static void main(String[] args) { try { Class<?> classObj = Class.forName("Student"); Student studentObj = (Student) classObj.newInstance(); Method method = classObj.getDeclaredMethod("showStudentFullName", null); method.setAccessible(true); /* * Parameters: * * obj - the object the underlying method is invoked from * * args - the arguments used for the method call * * Returns: the result of dispatching the method * represented by this object on obj with parameters args * */ method.invoke(studentObj, null); } catch (Exception e) { e.printStackTrace(); } } }Output
Peter JClick the below link to download the code: