How To Access Somebody Plain Too Method Using Reflection Inwards Java

Reflection inward Java is real powerful characteristic in addition to allows you lot to access private method in addition to fields which is non possible yesteryear 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 hence helpful. In final article nosotros receive got seen details nearly 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 alone accessible inward the shape they are declared exactly alongside reflection you lot tin telephone outcry upwards private method in addition to access private fields exterior the class. In this article nosotros volition run into uncomplicated instance of accessing private champaign using reflection in addition to invoking private method using reflection inward Java.

Accessing private fields inward Java using reflection

Reflection inward Java is real powerful characteristic in addition to allows you lot to  How to Access Private Field in addition to Method Using Reflection inward JavaIn gild to access private champaign using reflection, you lot require to know the call of champaign than yesteryear calling getDeclaredFields(String name) you lot volition acquire a java.lang.reflect.Field instance representing that field. retrieve using getDclaredFields() method in addition to not getFields() method which returns all non private fields both from sub shape in addition to super class. piece getDeclaredFields() returns both private in addition to non private fields declared inward the class. Once you lot acquire the champaign reference you lot require to piece of occupation into accessible yesteryear calling Field.setAccessible(true) because you lot are going to access private field. Now you lot tin acquire value or private champaign yesteryear calling Field.get(String field_name).if you lot don't telephone outcry upwards setAccessible(true) in addition to endeavor to access private champaign 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 alongside 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 receive got seen how to telephone outcry upwards a method yesteryear its String name in addition to nosotros volition role 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. transcend all the declaration type needed yesteryear method or zippo if method doesn't bring whatever argument. This volition laissez passer you lot instance of java.lang.reflect.Method which tin than survive used to telephone outcry upwards private method using reflection, every bit shown inward code example.

Code instance of accessing private champaign 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> individual = (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 champaign using reflection inward Java
            Person privateRyan = new Person("John" , "8989736353");
            Field privateField = person.getDeclaredField("phone");
         
            //this telephone outcry upwards allows individual fields to survive accessed via reflection
            privateField.setAccessible(true);
         
            //getting value of individual champaign using reflection
            String value = (String) privateField.get(privateRyan);          
         
            //print value of individual champaign 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

Belum ada Komentar untuk "How To Access Somebody Plain Too Method Using Reflection Inwards Java"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel