Preventing instantiation of a class if argument to

2020-06-14 03:36发布

I have a public constructor which takes a parameter (int age) to create an object. I want to check if the passed parameter is legal or not, for example age cannot be negative. If its illegal, then don't create an object/instance. If legal, no problem.

I can only think of one way to do this -

Make constructor private. Create a static method with parameter (int age) to do all the checking and return a null if you pass it an illegal value. If you pass it a legal value, then create an object and return its reference. Is there any other way of doing it ? Maybe from inside the constructor itself ?

EDIT : I thought of one problem with the above method. The factory method/object creator method can only be a static method for obvious reasons. What happens if the factory method has to access a member variable (to do some checking) to create an object ? Then, we will be forced to make that member variable static. This may not be okay in all cases.

Does it make sense ?

标签: java
4条回答
Rolldiameter
2楼-- · 2020-06-14 03:40

It will be better to use the static factory for this purposes. Because throwing an exception from a constructor is not very nice idea.

public class Person
{     
    public static Person newPerson(int age) /* throws SomeException -- if you want */ {
        if (age <= 0 || age >= 150) {
           return null; // or throw an Exception - it is how you want   
        }
        return new Person(age);
    }

    private Person(int age) {
        // assign age to field value
    }
}
查看更多
Ridiculous、
3楼-- · 2020-06-14 03:44

Is there any other way of doing it ? Maybe from inside the constructor itself ?

Yes. I suggest to throw an Exception from constructor

public class Person
{


    int age;
    public Person(int age) throws Exception
    {
       if(age <= 0)
       {

          throw new Exception("Age is not allowed");
       }
       // Do some stuffs
       this.age = age;
    }

}

Edit:

You can also use IllegalArgumentException as suggested by Till Helge Helwig

public class Person
{


    int age;
    public Person(int age) throws IllegalArgumentException
    {
       if(age <= 0)
       {

          throw new IllegalArgumentException("Age is not allowed");
       }
       // Do some stuffs
       this.age = age;
    }

}
查看更多
太酷不给撩
4楼-- · 2020-06-14 03:49

Consider this example, this is java.util.HashMap implementation

public HashMap(int initialCapacity, float loadFactor) {
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal initial capacity: " +
                                           initialCapacity);
    if (initialCapacity > MAXIMUM_CAPACITY)
        initialCapacity = MAXIMUM_CAPACITY;
    if (loadFactor <= 0 || Float.isNaN(loadFactor))
        throw new IllegalArgumentException("Illegal load factor: " +
                                           loadFactor);

    // Find a power of 2 >= initialCapacity
    int capacity = 1;
    while (capacity < initialCapacity)
        capacity <<= 1;

    this.loadFactor = loadFactor;
    threshold = (int)(capacity * loadFactor);
    table = new Entry[capacity];
    init();
}

see more in Effective Java 2nd Edition, Item 38: Check parameters for validity by Joshua Bloch, who is also the author of the above code

查看更多
够拽才男人
5楼-- · 2020-06-14 03:52

Rather throw Exception if parameter is illegal.

public Test(int age) throws IllegalArgumentException {
    if(age<0)
        throw new IllegalArgumentException(...);
    this.age = age;
}
查看更多
登录 后发表回答