简体   繁体   中英

How to create a create a generic class in Java but limit what types you can use?

I want a Fraction class that I can use to encapsulate data and logic regarding fractions, but I want to give the user the choice of what size integer they would like to use. Unfortunately, there is no common super class that covers only these classes: BigInteger, Long, Integer, Short

I would use Number , but I don't want to allow non-integer numbers like floats or decimals.

Can I do something like this?

import java.math.BigInteger;

public class Fraction<T> {

    private T numerator;
    private T denominator;

    Fraction(T numerator, T denominator) {
        if (!(T == BigInteger.class || T == Long.class || T == Integer.class || T == Short.class)) {
            throw new Exception();
        }
    }

}

The error I'm currently getting is T cannot be resolved to a variable

What I would do is just have Fraction<T extends Number> , but have only private constructors and all public methods that return an instance be specific to one of those types. (So, in theory, you could refer to Fraction<Float> , but it's only actually possible to get instances of Fraction that refer to integer-based types.)

You could have a check in your constructor like

if (numerator.doubleValue() / numerator.longValue() != 1)
{

    throw new IllegalArgumentException();
}

check both passed in numbers this way. this however would allow you to pass in something like 10.0, but IMHO, that's ok.

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