简体   繁体   English

如何在Java中实现对象级私有访问

[英]how to implement object-level private access in java

How could I make a member field private to this specific object ? 如何使成员字段私有于此特定对象 ie this object can read and modify the value, but other objects of the same class cannot. 即,该对象可以读取和修改值,但是同一类的其他对象则不能。

eg 例如

class Person 
{
    // don't mind sharing these with other persons :
    private integer houseNumber;
    private integer telephoneNumber;

    // would like this to be *really private*
    // (only visible / modifiable to this instance)
    private integer bankBalance;


    // Lots of code for interaction with other persons:
    // (e.g. maintained by co-workers)

    void interact1(Person person)
    {
        //Lots of code
    }

    void interact2(Person person)
    {
        //Lots of code
    }

    //...

    void interactN(Person person)
    {
        //Lots of code
    }
}

I understand that Java's 'private' access means access is restricted to code in this class. 我知道Java的“私有”访问权限意味着访问仅限于此类中的代码。 Conceptually all the code in the class is under my control so I am responsible for it. 从概念上讲,该类中的所有代码都在我的控制之下,所以我对此负责。 It should be my responsibilty to control what Person objects do to other Person objects. 控制Person对象对其他Person对象的作用是我的责任。

But say I have a large number of methods interacting with other persons, and I want the compiler to do the checking for me, rather than personally scouring the code. 但是说我有很多与其他人交互的方法,我希望编译器为我做检查,而不是亲自检查代码。 Maybe this java file is shared with co-workers, and changes frequently. 也许此Java文件与同事共享,并且经常更改。

My question is - how can I implement 'private to this object' access in Java? 我的问题是-如何在Java中实现“对此对象的私有”访问? Is there a sane / sensible way of achieving it? 是否有理智/明智的方式实现这一目标?

EDIT - re-emphasis of goals 编辑-重新强调目标

I want a few lines of class design / code, to guarantee that other Person objects can not read / write the bankBalance belonging to this instance. 我想要几行类设计/代码,以确保其他Person对象不能读取/写入属于此实例的bankBalance。 I know it's not really designed for in Java - but that's part of my motivation, to see what is the cleanest way to achieve it in general. 我知道它不是真正为Java设计的,但这是我的动机,以了解总体上最干净的方法是什么。 I really want the compiler to enforce it - I'm not looking for a solution that involves auditing all the functions, making sure they only call the correct getter / access method. 我真的希望编译器强制执行它-我不是在寻找涉及审核所有功能的解决方案,以确保它们仅调用正确的getter / access方法。

Assuming your purpose is to protect against accidents rather than malice, you could create a separate BankBalance class that keeps track of who owns the balance: 假设您的目的是防止意外而不是恶意,则可以创建一个单独的BankBalance类,该类跟踪谁拥有余额:

class BankBalance {
    private int bal;
    private Person belongsTo;
    public BankBalance (int initialBalance, Person belongsTo) {
        this.bal = initialBalance; this.belongsTo = belongsTo; 
    }
    public int getBalance (Person calledBy) {
        if (calledBy != belongsTo) throw new RuntimeException ("no peeking");
        return bal;
    }
}

class Person {
    private BankBalance bal;

    void checkBalance () {
        if (bal.getBalance(this) > 1000) ...
    }
}

Any use of getBalance would need the caller to pass this . 任何对getBalance使用都需要调用者传递this I think this might make it harder to accidentally write code that accessess another Person's balance. 我认为这可能会使得更难于意外地编写可达到他人平衡的代码。 You could also make BankBalance a nested class, and check calledBy != Person.this rather than needing an explicit belongsTo field, but that would allow interact1 to refer to person2.bal.bal (making bal private in BankBalance still wouldn't prevent the enclosing class from accessing it). 您还可以使BankBalance成为嵌套类,并检查calledBy != Person.this而不需要显式的belongsTo字段,但这将允许interact1引用person2.bal.bal (在BankBalance中将bal私有仍然不会阻止封闭类以使其无法访问)。 Maybe that's still good enough to prevent accidents. 也许这仍然足以防止发生事故。

As everyone pointed out there is no real way of doing this. 正如每个人都指出的那样,没有真正的方法可以做到这一点。 You could do something like a getter of the form 您可以做某种形式的吸气剂

private int getBankBalance(Object caller) {
     if (caller == this) {
          return bankBalance;
     } else {
          throw new RuntimeException("GTFO");
     }
}

and then enforcing that all access be done through object.getBankBalance(this) . 然后强制所有访问都通过object.getBankBalance(this)

However this does not stop people from accessing the bankBalance directly or calling object.getBankBalance(object) . 但是,这不会阻止人们直接访问bankBalance或调用object.getBankBalance(object)

You can declare an arraylist of balances that will contain each Persons balance. 您可以声明一个包含每个“人”余额的余额数组列表。 Something like this: 像这样:

static int instances = 0;
private int thisInstance = 0; 
private List<Integer> balances = new Arraylist<>();

public Person() {
   instances++;
   thisInstance = instances;
   balances.add(thisInstance, new Integer(0));
}

Then whenever you have code that interacts with the bankBalance you just return the same element as the instance that called it. 然后,只要您有与bankBalance交互的代码,您就只需返回与调用它的实例相同的元素。

For example, if the fifth instance tried to get it's balance, the method would return the fifth balance in the array. 例如,如果第五个实例试图获得其余额,则该方法将返回数组中的第五个余额。

For example: 例如:

private int getBankBalance() {
   return balances.get(thisInstance).intValue();
}

This will make it so anyone attempting to get their bank balance is only returned their balance, and they can't see anyone elses balance. 这样一来,任何试图获得银行存款余额的人都只能退还其存款余额,而看不到其他任何人的余额。

I don't believe that the direction you are taking is the correct one, if I were you I would try to see things from a different angle, it is a weird requirement the one you're asking. 我不认为您所采取的方向是正确的方向,如果我是您,我会尝试从不同的角度看待事情,这是您所要求的一个奇怪的要求。

You cannot achieve that if what you need is forbid the property access from other objects. 如果您需要禁止其他对象的属性访问,则无法实现。 You could do it if you specify a getter for it and use that to reference the property. 如果为它指定一个吸气剂并使用它来引用属性,则可以这样做。

An instance is identified by its attributes, so you could write a method that checks for certain properties and then use it to determine if a certain object could access that property accessor. 实例由其属性标识,因此您可以编写一种方法来检查某些属性,然后使用它来确定某个对象是否可以访问该属性访问器。

So to sum up it would be something like this: 因此,总结起来就是这样:

private boolean isBankBalanceAccessible() {
    // check that properties are those you want,
    // for example only when houseNumber is 1234567890
    return houseNumber == 1234567890;
}

private int getBankBalance() {
    if (isBankBalanceAccessible()) {
        return bankBalance;
    } else {
        // maybe throw here?
    }
}

I thought of this... 我想到了这个

     void interact1(Person person)
      {
         if(this==person)
          {
             person.bankBalance
             // Do here with the balance of the objecct which calls this function
          }


          //rest code here
      }

Hope it works..!! 希望它能工作.. !!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 对象级锁定是线程安全的吗? - Object-level locking is it thread-safe? 如何在 Java 中访问私有对象中的私有对象? - How to access a private object within a private object in Java? 如何在Java中实现用户级别的安全性和访问jsp页面的限制? - How to implement a user level security and restriction to access jsp pages in java? Java:使用私有字段进行对象访问 - Java : Object access with private fields 如何访问在Java中使用它的唯一类的私有嵌套类对象 - How to access a private nested class object of a sole class that uses it in java 如何修改私有访问对象? - How to modify a private access object? 使用Java反射API访问私有对象 - Access private object using java reflection api Java:如何实现私有抽象方法? - Java: how to implement private abstract methods? 在Java中,如何在Deque类的子类中实现新功能而不访问Deque类中的私有字段? - In Java, how can I implement new functionality in a subclass of a Deque class without access to the private fields in the Deque class? 子类对象如何访问父类的私有变量,就像java中一样,除了类本身可以访问私有变量之外,否? - How does the subclass object access the private variable of super class,as in java no except the class itself can access the private variable?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM