How To Access Someone Champaign As Well As Method Using Reflection Inward Java
Monday, September 24, 2018
Add Comment
Reflection inward Java is real powerful characteristic in addition to allows y'all to access private method in addition to fields which is non possible past times whatever other agency inward Java in addition to because of this characteristic of reflection many code coverage tool, static analysis tool in addition to Java IDE similar Eclipse in addition to Netbeans has been in addition to therefore helpful. In final article nosotros receive got seen details virtually private keyword inward Java in addition to learned why nosotros should ever brand fields in addition to method individual inward Java. There nosotros receive got mentioned that private fields in addition to methods are entirely accessible inward the degree they are declared merely amongst reflection y'all tin telephone telephone private method in addition to access private fields exterior the class. In this article nosotros volition come across elementary instance of accessing private plain using reflection in addition to invoking private method using reflection inward Java.
Accessing private fields inward Java using reflection
In lodge to access private plain using reflection, y'all necessitate to know the shout out of plain than past times calling getDeclaredFields(String name) y'all volition acquire a java.lang.reflect.Field instance representing that field. shout out upwards using getDclaredFields() method in addition to not getFields() method which returns all non private fields both from sub degree in addition to super class. patch getDeclaredFields() returns both private in addition to non private fields declared inward the class. Once y'all acquire the plain reference y'all necessitate to become far accessible past times calling Field.setAccessible(true) because y'all are going to access private field. Now y'all tin acquire value or private plain past times calling Field.get(String field_name).if y'all don't telephone telephone setAccessible(true) in addition to endeavor to access private plain using reflection y'all volition acquire Exception every bit shown inward below example
java.lang.IllegalAccessException: Class test.ReflectionTest tin non access a fellow member of class test.Person amongst modifiers "private"
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:65)
at java.lang.reflect.Field.doSecurityCheck(Field.java:960)
at java.lang.reflect.Field.getFieldAccessor(Field.java:896)
at java.lang.reflect.Field.get(Field.java:358)
at test.ReflectionTest.main(ReflectionTest.java:31)
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:65)
at java.lang.reflect.Field.doSecurityCheck(Field.java:960)
at java.lang.reflect.Field.getFieldAccessor(Field.java:896)
at java.lang.reflect.Field.get(Field.java:358)
at test.ReflectionTest.main(ReflectionTest.java:31)
Calling private methods inward Java using reflection
In our final Java tutorial on Reflection nosotros receive got seen how to telephone telephone a method past times its String name in addition to nosotros volition purpose that information hither for invoking individual method. Calling private method using reflection is similar to accessing private fields reflectively. Use getDeclaredMethods(String name, Class.. parameter) to acquire declared private method. top all the declaration type needed past times method or cipher if method doesn't convey whatever argument. This volition plough over y'all instance of java.lang.reflect.Method which tin than hold upwards used to telephone telephone private method using reflection, every bit shown inward code example.
Code instance of accessing private plain in addition to method using reflection
package test;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ReflectionTest {
public static void main(String args[]) throws ClassNotFoundException {
Class<Person> mortal = (Class<Person>) Class.forName("test.Person");
//getFields() does non supply individual field
System.out.println("Fields : " + Arrays.toString(person.getFields()));
//getDeclaredFields() supply both individual in addition to non individual fields using reflection
System.out.println("Declared Fields : " + Arrays.toString(person.getDeclaredFields()));
//getDeclaredMethods() supply both individual in addition to non individual methods using reflection
System.out.println("Declared methods : " + Arrays.toString(person.getDeclaredMethods()));
try {
//accessing value of individual plain using reflection inward Java
Person privateRyan = new Person("John" , "8989736353");
Field privateField = person.getDeclaredField("phone");
//this telephone telephone allows individual fields to hold upwards accessed via reflection
privateField.setAccessible(true);
//getting value of individual plain using reflection
String value = (String) privateField.get(privateRyan);
//print value of individual plain using reflection
System.out.println("private field: " + privateField + " value: " + value);
//accessing individual method using reflection
Method privateMethod = person.getDeclaredMethod("call");
//making individual method accessible using reflection
privateMethod.setAccessible(true);
//calling individual method using reflection inward java
privateMethod.invoke(privateRyan);
} catch (InvocationTargetException ex) {
Logger.getLogger(ReflectionTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchMethodException ex) {
Logger.getLogger(ReflectionTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(ReflectionTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(ReflectionTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchFieldException ex) {
Logger.getLogger(ReflectionTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(ReflectionTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
class Person{
public String name;
private String phone;
public Person(String name, String phone){
this.name = name;
this.phone = phone;
}
private void call(){
System.out.println("Calling " + this.name +" at " + this.phone);
}
public String getName(){
return name;
}
}
Output:
Fields : [public java.lang.String test.Person.name]
Declared Fields : [public java.lang.String test.Person.name, private java.lang.String test.Person.phone]
Declared methods : [public java.lang.String test.Person.getName(), private void test.Person.call()]
private field: private java.lang.String test.Person.phone value: 8989736353
Calling John at 8989736353
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ReflectionTest {
public static void main(String args[]) throws ClassNotFoundException {
Class<Person> mortal = (Class<Person>) Class.forName("test.Person");
//getFields() does non supply individual field
System.out.println("Fields : " + Arrays.toString(person.getFields()));
//getDeclaredFields() supply both individual in addition to non individual fields using reflection
System.out.println("Declared Fields : " + Arrays.toString(person.getDeclaredFields()));
//getDeclaredMethods() supply both individual in addition to non individual methods using reflection
System.out.println("Declared methods : " + Arrays.toString(person.getDeclaredMethods()));
try {
//accessing value of individual plain using reflection inward Java
Person privateRyan = new Person("John" , "8989736353");
Field privateField = person.getDeclaredField("phone");
//this telephone telephone allows individual fields to hold upwards accessed via reflection
privateField.setAccessible(true);
//getting value of individual plain using reflection
String value = (String) privateField.get(privateRyan);
//print value of individual plain using reflection
System.out.println("private field: " + privateField + " value: " + value);
//accessing individual method using reflection
Method privateMethod = person.getDeclaredMethod("call");
//making individual method accessible using reflection
privateMethod.setAccessible(true);
//calling individual method using reflection inward java
privateMethod.invoke(privateRyan);
} catch (InvocationTargetException ex) {
Logger.getLogger(ReflectionTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchMethodException ex) {
Logger.getLogger(ReflectionTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(ReflectionTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(ReflectionTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchFieldException ex) {
Logger.getLogger(ReflectionTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(ReflectionTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
class Person{
public String name;
private String phone;
public Person(String name, String phone){
this.name = name;
this.phone = phone;
}
private void call(){
System.out.println("Calling " + this.name +" at " + this.phone);
}
public String getName(){
return name;
}
}
Output:
Fields : [public java.lang.String test.Person.name]
Declared Fields : [public java.lang.String test.Person.name, private java.lang.String test.Person.phone]
Declared methods : [public java.lang.String test.Person.getName(), private void test.Person.call()]
private field: private java.lang.String test.Person.phone value: 8989736353
Calling John at 8989736353
Further Learning
Complete Java Masterclass
Why String is immutable inward Java
0 Response to "How To Access Someone Champaign As Well As Method Using Reflection Inward Java"
Post a Comment