简体   繁体   中英

Is there any way to ensure type safety in java at compile time without generics

I am writing a java application using older version of java SDK which doesn't support Generics. So, How can I assure type safety during compile time. I can use instanceof(). But, it does ensure run time type safety. Please provide your suggestions.

You need to either uses abstract/interfaces (ie limit things by making them all implement the same interface) or you need to use generics.

There aren't many other options, this is exactly what generics was added to solve.

In the bad old days, collections and maps were typically stuffed inside a class whose methods expose the right types. So, to create a "typesafe" list of integers, you might do something like:

class IntegerList {
    private final List delegate = new ArrayList();

    public boolean add(Integer i) {
        return delegate.add(i);
    }

    public Integer get(int index) {
        return (Integer) delegate.get(i);
    }

    public Iterator iterator() {
        return delegate.iterator();
    }

    // etc
}

Of course, you're stuck with a non-typesafe Iterator , but you could achieve that with another similar IntegerIterator . Note that this is basically what generics does for you automatically.

Why are you using such an antiquated JDK?

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