我需要 getter 和 setter 以及额外的实体构造函数吗? [英] Do I need getters and setters and extra entity constructors?

查看:48
本文介绍了我需要 getter 和 setter 以及额外的实体构造函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Android 项目中使用 ORMLite 进行数据库持久化.从示例中看起来一切都很好.当我开始使用它时,我发现我并没有完全理解它的要求和行为.

I am trying to use ORMLite for database persistence in Android project. It looks all good from examples. Once I start to use it, I found I do not completely understand its requirement and behavior.

假设我有一个名为 Bone 的类,我想保留它.

Let's say I have a class called Bone which I would like to persist.

@DatabaseTable(tableName = "bones")
public class Bone{
// user defined
@DatabaseField(dataType = DataType.STRING)
private String color;
@DatabaseField
private double length;
@DatabaseField
private int quantity;

// db assigned
@DatabaseField(generatedId = true)
private int id;
public Bone(){
}

// constructors
public Bone(String color, int quantity) {
    this(color, quantity, 0);
}
public Bone(String color, int quantity, int id) {
    this.color = color;
    this.quantity = quantity;
    this.id = id;
}

public Bone(Bone old, int id){
    this.color = old.color;
    this.length = old.length;
    this.quantity = old.quantity;
    this.id = id;
}

public String getColor() {
    return color;
}
public double getLength() {
    return length;
}

public int getQuantity() {
    return quantity;
}
public void setLength(double length) {
    this.length = length;
}

public int getId() {
    return id;
}
}

  1. 其字段的getter和setter的名称有什么要求?他们的名字有什么区别吗?我可以在没有 getter 和 setter 的情况下使用一个吗?

  1. What are the requirements for the names of getters and setters of its fields? Does their names make any difference? Can I use one without getter and setter?

除了没有arg构造函数,还需要其他构造函数吗?

Besides no arg constructor, any other constructor is needed?

请帮忙.

推荐答案

1) 其字段的getter和setter的名称有什么要求?他们的名字有什么区别吗?我可以使用没有 getter 和 setter 的方法吗?

1) What are the requirements for the names of getters and setters of its fields? Does their names make any difference? Can I use one without getter and setter?

对 getter 和 setter 没有要求.默认情况下,ORMLite 使用反射直接构建实体字段.

There are no requirements for getters and setters. By default ORMLite uses reflection to build the entity fields directly.

如果您设置了 useGetSet = true @DatabaseField 注释的字段 然后你就可以使用 get/set 方法.有关格式,请参阅 javadoc.

If you set the useGetSet = true field of the @DatabaseField annotation then you do neet get/set methods. See the javadocs for the format.

2) 除了没有arg构造函数,还需要其他构造函数吗?

2) Besides no arg constructor, any other constructor is needed?

没有.在反射工作之前,您只需要一个可访问的 ORMLite 无参数构造函数来实例化对象.

No. You only need an accessible no-arg constructor for ORMLite to instantiate the object prior to the reflection work.

这篇关于我需要 getter 和 setter 以及额外的实体构造函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆