简体   繁体   English

从扩展类访问属性

[英]Accessing properties from an extended class

I'm trying to crate a Model structure, to access a database, inspired by Laravel's Eloquent (PHP). 我试图创建一个模型结构,以访问受Laravel Eloquent(PHP)启发的数据库。

Basically I've got a class called Model , and for now it's just empty. 基本上,我有一个名为Model的类,现在它只是空的。

I then got another class called User , which extends Model 然后,我得到了另一个名为User类,该类扩展了Model

public class User extends Model {

    private String table = "users";
}

As you can see the User class also got a property called table, which refers to the table on the database the model is representing. 如您所见,User类还具有一个名为table的属性,该属性引用模型所代表的数据库上的表。

Inside of my Model.java I'm then trying to fetch the name of the table. 然后,在我的Model.java内部,尝试获取表的名称。

So far I'm running some code on my Model.java constructor where I go through all of the fields, on the instance. 到目前为止,我正在Model.java构造函数上运行一些代码,在Model.java构造函数中我遍历了实例上的所有字段。 This gives me a Field object, but I'm unable to get the content of table from Model.java 这给了我一个Field对象,但是我无法从Model.java获取表的内容。

Model.java : Model.java

public abstract class Model {

    public Model()
    {
        List<Field> fields = new ArrayList<>();
        for (Class<?> c = this.getClass(); c != null; c = c.getSuperclass()) {
            fields.addAll(Arrays.asList(c.getDeclaredFields()));
        }
        for (Field field : fields)
        {
            String name = field.getName(); //returns "table"
        }
    }
}

All In all, what I need to is to get the table name from the class that's extends model. 总之,我需要从扩展模型的类中获取表名。

Any ideas? 有任何想法吗? or is this a bad practice? 还是这是不好的做法?

Model should have an abstract method, getTableName 模型应该有一个抽象方法getTableName

Yes it is bad practice because a class should not know details about class that inherit from it. 是的,这是不好的做法,因为一个类不应该知道有关从其继承的类的详细信息。

The way you are doing it, there's no contract that specifies that a subclass must implement that field. 在执行此操作时,没有合同指定子类必须实现该字段。

By creating a method that has to be implemented by subclass, there's a clear contract and you are applying the dependency inversion principle. 通过创建必须由子类实现的方法,可以达成明确的约定,并且您将应用依赖关系反转原理。 See https://en.m.wikipedia.org/wiki/Dependency_inversion_principle 参见https://en.m.wikipedia.org/wiki/Dependency_inversion_principle

public abstract class Model {

    public Model() {}

    abstract String getTableName();
}

public class User extends Model() {
    public String getTableName(){
      return "users";
    }
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM