How To Access Someone Champaign In Addition To Method Using Reflection Inwards Java

Reflection inward Java is really powerful characteristic together with allows you lot to access private method together with fields which is non possible past times whatever other way inward Java together with because of this characteristic of reflection many code coverage tool, static analysis tool together with Java IDE similar Eclipse together with Netbeans has been together with then helpful. In final article nosotros direct maintain seen details virtually private keyword inward Java together with learned  why nosotros should ever brand fields together with method individual inward Java. There nosotros direct maintain mentioned that private fields together with methods are alone accessible inward the cast they are declared precisely amongst reflection you lot tin telephone phone private method together with access private fields exterior the class. In this article nosotros volition come across unproblematic representative of accessing private plain using reflection together with invoking private method using reflection inward Java.

Accessing private fields inward Java using reflection

Reflection inward Java is really powerful characteristic together with allows you lot to  How to Access Private Field together with Method Using Reflection inward JavaIn social club to access private plain using reflection, you lot demand to know the yell of plain than past times calling getDeclaredFields(String name) you lot volition acquire a java.lang.reflect.Field event representing that field. yell upwards using getDclaredFields() method together with not getFields() method which returns all non private fields both from sub cast together with super class. spell getDeclaredFields() returns both private together with non private fields declared inward the class. Once you lot acquire the plain reference you lot demand to operate into accessible past times calling Field.setAccessible(true) because you lot are going to access private field. Now you lot tin acquire value or private plain past times calling Field.get(String field_name).if you lot don't telephone phone setAccessible(true) together with attempt to access private plain using reflection you lot 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)

Calling private methods inward Java using reflection

In our final Java tutorial on Reflection nosotros direct maintain seen how to telephone phone a method past times its String name together with 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. operate past times all the declaration type needed past times method or cipher if method doesn't direct maintain whatever argument. This volition laissez passer you lot event of java.lang.reflect.Method which tin than hold upwards used to telephone phone private method using reflection, every bit shown inward code example.

Code representative of accessing private plain together with 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> somebody = (Class<Person>) Class.forName("test.Person");
     
        //getFields() does non furnish individual field
        System.out.println("Fields : " + Arrays.toString(person.getFields()));
     
        //getDeclaredFields() furnish both individual together with non individual fields using reflection
        System.out.println("Declared Fields : " + Arrays.toString(person.getDeclaredFields()));      
           
        //getDeclaredMethods() furnish both individual together with 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 phone 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 In Addition To Method Using Reflection Inwards Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel