如何知道一个实例的所有成员变量都没有被设置?

发布于 2024-11-25 14:28:43 字数 516 浏览 3 评论 0原文

假设我在 Java 中创建了一个 Person 类的实例,

public class Person
{
 private String name;
 private int age;
 // lot of other member variables
 // get set here
}

如何知道该实例是否至少设置了一个成员变量(无需一一检查所有变量?

例如:

Person person  = new Person();
Person person1 = new Person();
person1.setName("John");

我需要知道 person 实例没有设置) person1 至少设置了一个变量,

我认为解决这个问题的办法是

  1. 创建一个布尔标志,在每个 set 方法中将其更改为 true,或者
  2. 创建一个逐个检查变量的方法。

但是 如果有更优雅的方法 这。

Let's say I created an instance in Java of a class Person

public class Person
{
 private String name;
 private int age;
 // lot of other member variables
 // get set here
}

How to know whether this instance at least have one of member variables being set (without checking all of the variables one by one?

For example :

Person person  = new Person();
Person person1 = new Person();
person1.setName("John");

I need to know that person instance has not set any variables. However person1 has set at least one variable.

What I can think for solving this is to

  1. create boolean flag that being changed to true in every set method, or
  2. create a method that checking the variables one by one.

But I wonder if there's some way that more elegant to do this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧城烟雨 2024-12-02 14:28:43

这是完成此任务的一种方法(不建议用于生产,因为它不能很好地检查 javabean 样式变量)。

这样你只需调用

Helper.hasSomethingBeenSetted

以对象作为参数。

package com.intellij.generatetestcases.javadoc;

import java.lang.*;
import java.lang.reflect.*;
import java.util.*;
import java.util.regex.*;

import static com.intellij.generatetestcases.javadoc.Person.Helper.hasSomethingBeenSetted;

public class Person {

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    private String name;
    private int age;

    // lot of other member variables
    // get set here
    public static void main(java.lang.String[] args) throws InvocationTargetException, IllegalAccessException {

        Person person = new Person();
        System.out.println("has been set something: " + hasSomethingBeenSetted(person));

        Person person1 = new Person();
        person1.setAge(3);
        System.out.println("has been set something: " + hasSomethingBeenSetted(person1));


        Person person2 = new Person();
        person2.setName("john");
        System.out.println("has been set something: " + hasSomethingBeenSetted(person2));

    }

    public  static class Helper {

        public static boolean hasSomethingBeenSetted(Person person) throws IllegalAccessException, InvocationTargetException {
            // TODO get all javabean style attributes

            // TODO flag to indicate something has been set, false by default
            boolean somethingSetted = false;

            Class<? extends Person> aClass = person.getClass();
            Method[] methods = aClass.getMethods();
            for (Method method : methods) {
                if (method.getDeclaringClass().equals(aClass) && method.getModifiers() == Modifier.PUBLIC) {
                    Matcher matcher = Pattern.compile("get(\\p{Lu}[a-zA-Z]*)").matcher(method.getName());
                    if (matcher.find()) {
                        // assuming there is a getter FIXME check manually this
                        Object value = method.invoke(person);
                        if (value != null) {
                            Class<? extends Object> clazz = value.getClass();
                            if (isWrapperType(clazz)) {
                                if (clazz.equals(Boolean.class)) {
                                    if (DEFAULT_BOOLEAN != (Boolean) value) {
                                        somethingSetted = true;
                                    }
                                } else if (clazz.equals(Byte.class)) {
                                    if (DEFAULT_BYTE != (Byte) value) {
                                        somethingSetted = true;
                                    }
                                } else if (clazz.equals(Short.class)) {
                                    if (DEFAULT_SHORT != (Short) value) {
                                        somethingSetted = true;
                                    }
                                } else if (clazz.equals(Integer.class)) {
                                    if (DEFAULT_INT != (Integer) value) {
                                        somethingSetted = true;
                                    }
                                } else if (clazz.equals(Long.class)) {
                                    if (DEFAULT_LONG != (Long) value) {
                                        somethingSetted = true;
                                    }
                                } else if (clazz.equals(Float.class)) {
                                    if (DEFAULT_FLOAT != (Float) value) {
                                        somethingSetted = true;
                                    }
                                } else if (clazz.equals(Double.class)) {
                                    if (DEFAULT_DOUBLE != (Double) value) {
                                        somethingSetted = true;
                                    }
                                }
                            } else {
                                somethingSetted = true;
                            }
                        }

                    }
                }
            }
            return somethingSetted;
        }

        private static final HashSet<Class<?>> WRAPPER_TYPES = getWrapperTypes();


        public static boolean isWrapperType(Class<?> clazz) {
            return WRAPPER_TYPES.contains(clazz);
        }

        private static HashSet<Class<?>> getWrapperTypes() {
            HashSet<Class<?>> ret = new HashSet<Class<?>>();
            ret.add(Boolean.class);
            ret.add(Character.class);
            ret.add(Byte.class);
            ret.add(Short.class);
            ret.add(Integer.class);
            ret.add(Long.class);
            ret.add(Float.class);
            ret.add(Double.class);
            ret.add(Void.class);
            return ret;
        }

        private static boolean DEFAULT_BOOLEAN;
        private static byte DEFAULT_BYTE;
        private static short DEFAULT_SHORT;
        private static int DEFAULT_INT;
        private static long DEFAULT_LONG;
        private static float DEFAULT_FLOAT;
        private static double DEFAULT_DOUBLE;
    }


}

This is one way to get this done (not recommended for production because it doesn't check well for javabean style variables).

With this you only have to call

Helper.hasSomethingBeenSetted

with the object as parameter.

package com.intellij.generatetestcases.javadoc;

import java.lang.*;
import java.lang.reflect.*;
import java.util.*;
import java.util.regex.*;

import static com.intellij.generatetestcases.javadoc.Person.Helper.hasSomethingBeenSetted;

public class Person {

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    private String name;
    private int age;

    // lot of other member variables
    // get set here
    public static void main(java.lang.String[] args) throws InvocationTargetException, IllegalAccessException {

        Person person = new Person();
        System.out.println("has been set something: " + hasSomethingBeenSetted(person));

        Person person1 = new Person();
        person1.setAge(3);
        System.out.println("has been set something: " + hasSomethingBeenSetted(person1));


        Person person2 = new Person();
        person2.setName("john");
        System.out.println("has been set something: " + hasSomethingBeenSetted(person2));

    }

    public  static class Helper {

        public static boolean hasSomethingBeenSetted(Person person) throws IllegalAccessException, InvocationTargetException {
            // TODO get all javabean style attributes

            // TODO flag to indicate something has been set, false by default
            boolean somethingSetted = false;

            Class<? extends Person> aClass = person.getClass();
            Method[] methods = aClass.getMethods();
            for (Method method : methods) {
                if (method.getDeclaringClass().equals(aClass) && method.getModifiers() == Modifier.PUBLIC) {
                    Matcher matcher = Pattern.compile("get(\\p{Lu}[a-zA-Z]*)").matcher(method.getName());
                    if (matcher.find()) {
                        // assuming there is a getter FIXME check manually this
                        Object value = method.invoke(person);
                        if (value != null) {
                            Class<? extends Object> clazz = value.getClass();
                            if (isWrapperType(clazz)) {
                                if (clazz.equals(Boolean.class)) {
                                    if (DEFAULT_BOOLEAN != (Boolean) value) {
                                        somethingSetted = true;
                                    }
                                } else if (clazz.equals(Byte.class)) {
                                    if (DEFAULT_BYTE != (Byte) value) {
                                        somethingSetted = true;
                                    }
                                } else if (clazz.equals(Short.class)) {
                                    if (DEFAULT_SHORT != (Short) value) {
                                        somethingSetted = true;
                                    }
                                } else if (clazz.equals(Integer.class)) {
                                    if (DEFAULT_INT != (Integer) value) {
                                        somethingSetted = true;
                                    }
                                } else if (clazz.equals(Long.class)) {
                                    if (DEFAULT_LONG != (Long) value) {
                                        somethingSetted = true;
                                    }
                                } else if (clazz.equals(Float.class)) {
                                    if (DEFAULT_FLOAT != (Float) value) {
                                        somethingSetted = true;
                                    }
                                } else if (clazz.equals(Double.class)) {
                                    if (DEFAULT_DOUBLE != (Double) value) {
                                        somethingSetted = true;
                                    }
                                }
                            } else {
                                somethingSetted = true;
                            }
                        }

                    }
                }
            }
            return somethingSetted;
        }

        private static final HashSet<Class<?>> WRAPPER_TYPES = getWrapperTypes();


        public static boolean isWrapperType(Class<?> clazz) {
            return WRAPPER_TYPES.contains(clazz);
        }

        private static HashSet<Class<?>> getWrapperTypes() {
            HashSet<Class<?>> ret = new HashSet<Class<?>>();
            ret.add(Boolean.class);
            ret.add(Character.class);
            ret.add(Byte.class);
            ret.add(Short.class);
            ret.add(Integer.class);
            ret.add(Long.class);
            ret.add(Float.class);
            ret.add(Double.class);
            ret.add(Void.class);
            return ret;
        }

        private static boolean DEFAULT_BOOLEAN;
        private static byte DEFAULT_BYTE;
        private static short DEFAULT_SHORT;
        private static int DEFAULT_INT;
        private static long DEFAULT_LONG;
        private static float DEFAULT_FLOAT;
        private static double DEFAULT_DOUBLE;
    }


}
掩于岁月 2024-12-02 14:28:43

我想说我们应该在 Person 类上有一个状态检查方法,应该在使用 Person 实例之前调用该方法(作为从数据库过滤数据的机制)。事实上,建立一个单独的类来处理这个问题(而不是使用 person)可能是一个好主意,它也可以用于其他实体。然后,这个类可以发展(可以扩展)来处理检查我们是否需要针对不同实体的不同逻辑。

I would say we should have a state checking method on the Person class which should be called just before you use the Person instance (as a mechanism to filter data from database). In-fact it might be a good idea to set up a separate class to handle this(not use person), which can be used for other entities too. This class can then evolve (can be extended) to handle checking if we need different logic for different entities.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文