mardi 22 octobre 2019

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.





Aucun commentaire:

Enregistrer un commentaire