简体   繁体   中英

How to use field name of one class in a method of another class, such that get compiler issue if name is changed

I want to refer a field name in one class of java to another, such that I would get at least compiler error when someone changes the field name in base class.

Ex:

@Entity
class Employee {

    public String userId;
    public String timestampCreate;

}

class EmployeeReport {

    public Page<Employee> getEmployees() {

        return page = employeeJpaRepository.findAll(pageNumber, pageSize,
                Sort.by(Sort.Direction.DESC, "timestampCreate"));

    }

}

Here timestampCreate is the field name of Employee class.

I do not want to hardcode the column name; as it is bad practice and want it to be future proof, in case the field name changes. ie for example if someone changes the column name 'timestampCreate' to 'timestamp', then at lease I would like to see some compiler error in the EmployeeReport class.

Please suggest an idea. Thanks!

Note: I am opening this similar to previous one, coz that was incorrectly closed saying duplicate, whereas if you can see the marked answer nowhere answers my question!

You can't out of the box, but you could use annotations or reflection. IMO those are ugly solutions for such a use case, see the following answers for more details. nameof equivalent in Java

You can get this to work by either using Querydsl or the JPA metamodel. The fundamental idea is that you register an APT that will generate metamodel types that expose the fields of the entity as properties in turn. Eg the Hibernate APT will create a type Employee_ that contains a public field timestampCreate . You can then use these properties to build type safe Sort instances via

new JpaSort(Employee_.timestampCreate)

You can even build nested paths using the static path method on JpaSort :

new JpaSort(JpaSort.path(Department_.head).dot(Employee_.timestampCreate));

That assumes an additional entity type Department with a property head of type Employee .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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