mercredi 12 avril 2017

Unable to access private method in java using Reflection API

I am getting following error when i try to access the private method using reflection.

Here is the sample code,

public class Bank {

    public final static String name="Nanda Bank";

    public int value;

    public double getRatOfInterest(){

        return (double) 10.5;
    }

    private void getDetails(){

        System.out.println("User Password 123");
    }
}

public class JavaReflectionPrivateExample {

public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {

// getting private method. unable to access private method using reflection api

Class<Bank> c = Bank.class;
Method privateMethod = c.getMethod("getDetails");

privateMethod.setAccessible(true);
privateMethod.invoke(c.newInstance());

    }
}

Getting following exception when i execute JavaReflectionPrivateExample:

Exception in thread "main" java.lang.NoSuchMethodException: 
com.nanda.java.testlab.oops.Bank.getDetails()
    at java.lang.Class.getMethod(Unknown Source)
    at com.nanda.java.testlab.reflections.JavaReflectionPrivateExample.main(JavaReflectionPrivateExample.java:24)





Aucun commentaire:

Enregistrer un commentaire