如何在Java中获取实例名称?

时间:2015-04-27 23:08:59

标签: java

我想知道我们是否可以在Java中获取实例名称。例如:

from rest_framework import serializers

class CommentSerializer(serializers.Serializer):
    email = serializers.EmailField()
    content = serializers.CharField(max_length=200)
    created = serializers.DateTimeField()

我的期望结果是:

//Rights array (WRITE, CREATE, DELETE, ADDUSERS, DELETE USERS)
function addUser($requester, $username, $rights) {
    $file = $requester->getFolder() . "Projects/" . $this->name . "/Data/users.json";
    $json = json_decode(file_get_contents($file, false));
    $json[$username] = array("write" => $rights[0], "create" => $rights[1], "delete" => $rights[2], "adduser" => $rights[3], "deleteuser" => $rights[4]);
    file_put_contents($file, json_encode($json));
}   

无论如何得到这个?

1 个答案:

答案 0 :(得分:5)

这在Java中是不可能的,甚至不能通过反思来获得。您最好的选择是在String字段中存储变量的名称,并在创建对象引用时填写此字段。

class A {
    private final String name;
    public A(String name) {
        this.name = name;
    }
    public void run() {
        System.out.println("Name: " + this.name);
    }
}
//...
A p = new A("p");
A q = new A("q");