Is there a way to access private method in inner-class with or without reflection

I'm trying to make a simple example of a user and bank program where you must guarantee that money cannot be cheated by someone who can add, inherit, implement current existing classes but cannot edit the initial ones. So I ask if you somehow can set someone's account's balance without the provided function for money transfer.

I've tried using reflection but you have to have public constructors to make an object on which you call the private methods but since everything is private I cant call it.

public class Bank {
    private static Bank ourInstance = new Bank();
    public static Bank getInstance() {
        return ourInstance;
    }

    private Bank() {}

    public boolean requestTransfer(User user1, User user2, double amount) {
        BankAccount ba1 = (BankAccount) user1.getBankAccount();
        BankAccount ba2 = (BankAccount) user2.getBankAccount();
        if (!(hasAccount(ba1) && hasAccount(ba2)))
            return false;

        if (ba1.getBalance() >= amount)
        {
            ba1.setBalance(ba1.getBalance() - amount);
            ba2.setBalance(ba2.getBalance() + amount);
            return true;
        }
        return false;
    }

    private class BankAccount implements BankAccountInterface {
        private double balance;
        private User user;

        private BankAccount(double balance) {
            this.balance = balance;
        }

        @Override
        public double getBalance() {
            return balance;
        }

        @Override
        public User getUser() {
            return user;
        }

        public void setUser(User user) {
            this.user = user;
        }

        private void setBalance(double balance) {
            this.balance = balance;
        }
    }
}

public interface BankAccountInterface {
    double getBalance();
    User getUser();
}

public class User {
    private String username;
    private String password;
    private Date created_at;
    private BankAccountInterface bankAccount;
    //constructor getters and setters etc..
}

If you can add your own classes inherit current ones, use reflection or anything at your disposal can you illegally give a user money.

That's a security question. You can use security manager settings preventing reflection, see this and this, interface changes by byte code manipulation is out of question after the class has loaded, see this. There are are other security vulnerabilities though, here's the official list, with the infamous deserialization vulnerability initially being there by design. Those are known issues without taking into consideration zero day exploits. Here's a more detailed discussion about the intricacies of security manager and certain APIs related to this exploit.

Can somebody tell me that how can i access private method of an inner class using reflection. There is a scenario like class A {class B {private fun() {-----}}} now i want to use method fun() of an inner class inside third class i.e "class c". Can i use reflection in someway to access this private method fun() in class c.

Here is reflection code for giving a known user $1,000,000:

User user = /*assigned elsewhere*/;

// Get users bank account
Field bankAccountField = user.getClass().getDeclaredField("bankAccount");
bankAccountField.setAccessible(true); // Bypass 'private'
Object bankAccount = bankAccountField.get(user);

// Get bank account balance
Field balanceField = bankAccount.getClass().getDeclaredField("balance");
balanceField.setAccessible(true); // Bypass 'private'
double balance = (Double) balanceField.get(bankAccount);

// Add $1,000,000 to bank account
balance += 1_000_000;
balanceField.set(bankAccount, balance);

With dp4j it is possible to test private members without directly using the Reflection API but simply accessing them as if they were accessible from the testing method; dp4j injects the needed Reflection code at compile-time. ↑ What's the best way of unit testing private methods?, March 7, 2011 ↑ Reflection API injected at compile-time

Once you have an instance of the inner object, you can use reflection to invoke the method itself:

Method someMethod = innerObject.getClass().getDeclaredMethod("someMethod", Integer.class);
someMethod.setAccessible(true);
someMethod.invoke(innerObject, 5);

in this example you provided,you can still use reflection for getting methods in User Class.

If you can add your own classes inherit current ones, use reflection or anything at your disposal can you illegally give a user money?Yes possible if methods are implemented without access restrictions for outer class,it is about security rather about java code.

No, you shouldn't do it all. If you hack into it via reflection, your code can stop working after installing any hotfix and you would find it only at runtime, which isn't the situation where you should put yourself and your client.

To access a private method you will need to call the Class.getDeclaredMethod (String name, Class [] parameterTypes) or Class.getDeclaredMethods () method. The methods Class.getMethod (String name, Class [] parameterTypes) and Class.getMethods () methods only return public methods, so they won't work.

You 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. Required methods of Method class

Write an inner class in it, return the private members from a method within the inner class, say, getValue (), and finally from another class (from which you want to access the private members) call the getValue () method of the inner class. To instantiate the inner class, initially you have to instantiate the outer class.

Comments
  • you can make reflection a bit harder using a SecurityManager, but probably never make it impossible at all (as @curiosa just also answered, but deleted (and undeleted))
  • Depends on access to application, if you will block ALL reflections and unsafe code with security manager, and maybe use java modules to limit access between modules and such person does not have access to machine itself - then it should be safe. But you ale also very limited with libraries and they can't use reflections too. (otherwise it really hard to limit reflections, as some library might give access to reflections too) But with access to app itself you can always strip all security with few arguments added to start line.
  • Bank setups always have maximum paranoia level, hard to imagine, they let you type that kind of jvm arguments anywhere.
  • It is possible to edit bytecode after class is loaded, but you need to have access to either reflections or to application starting arguments, as the provided links kinda suggest that bytecode is immutable after loading the class.
  • Can you provide an example or reference for the claim?
  • simplest way is to use ByteBuddyAgent library to get Instrumentation instance in runtime, and Instrumentation api allows you to change java classes at runtime as long as you don't add/remove/edit fields/method/class signature. But code inside every method can be edited. (before class is loaded everything can be edited, you can even relocate whole libraries at runtime as you can find in one of my answers). You can also see my method on jvm 8 that allows you to attach agent to yourself using only reflections on non-JDK JVM github.com/raphw/byte-buddy/issues/374#issuecomment-343786107
  • Instrumentation API docs.oracle.com/javase/7/docs/api/java/lang/instrument/…
  • Indeed but the inner class is private so the instance can only exist inside the outer-class which cannot be edited because that's part of the rules.
  • check this answer,it would help you understand.stackoverflow.com/questions/14112166/…