java - java中是否可以从对象中删除属性(变量)?

标签 java object reflection attributes

我有很多从一个类扩展而来的类

我还有一种方法,其参数是父类,并根据这些类的属性创建查询。

有时我需要忽略结果查询中的某些属性。

那么是否可以删除对象的某些属性?

class A1 extends Model {
    public String field1 = "";
    public String field2 = "";

    public String table = "A1";

    @Override
    public String getTable() {
        return this.table;
    }
}

class A2 extends Model {
    public String field1 = "";
    public String field2 = "";
    public String field3 = "";

    public String table = "A2";

    @Override
    public String getTable() {
        return this.table;
    }
}

class Utility {
    public static String query(Model params) {
        Field[] fields = params.getClass().getFields();
        String head = "INSERT INTO " + params.getTable() + "(";
        String tail = "VALUES (";
        for(Field field : fields) {
            String key = field.getName();
            String val;
            try {
                val = field.get(params);
            } catch (Exception e) {
                val = null;
            }
            head += key + ",";
            tail += "'" + val + "',";
        }
        head = head.substring(head,0,head.length() -1) + ")";
        tail = tail.substring(tail,0,tail.length() -1) + ")";
        return head + tail;
    }
}

我通过发送一个模型来调用查询方法

A1 data = new A1();
data.field1 = "Name";
data.field2 = "Family";
String query = Utility.query(data);

我只想从查询中删除 field2 我该怎么做?

感谢您的帮助

最佳答案

您可以实现注释。我们将其命名为@DontPersist。用它来标记不应持久化的字段。在 Utility.query() 中,您可以通过反射检查注释。

关于java - java中是否可以从对象中删除属性(变量)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23992599/

相关文章:

c# - 在 IL Emit 中将对象添加到循环列表 - 公共(public)语言运行时检测到无效程序

java - 使用 this.getClass().getDeclaredField 方法时出现 NullPointerException

java - Libgdx 在我填写 .fnt 时加载寻找 .png 的字体

Java 桌面应用程序和功能授权

Javascript:在 JavaScript 中是否有等同于 lua 的 _G?

c++ - 指向对象数组的指针作为成员覆盖内存

java - 如何纠正 "The injection target must not be declared static."警告

java - 序列化Java标准类时LocalClass不兼容

c# - 如何将包含 IList<class> 的对象转换为 DataTable,该对象还包含 6 个属性 - 4 个字符串、1 个 IList<anotherclass>、1 个 IList<string> ?

c# - 有没有更快/更好的方法来获取在 C# 中应用属性的方法