Java generic parameters are scoped to any type

Is there a syntax or solution to restrict generic type parameters to any type?

I know you can limit types to all types of all types (i.e. and logic):

public class MyClass<T extends Comparable<T> & Serializable> { } // legal Syntax

There is an or logical version, which is like this:

public class MyClass<T extends Comparable<T> | Serializable> { } // illegal Syntax

If there is no syntax supporting this (I don't think so), is there a good pattern solution or method?

For some contexts, a use case may be:

/** @return true if the obj is either has the same id,or if obj is the same as id */
public <T extends MyClass | String> boolean sameAs(T obj) {
    if (obj instanceof String) return this.id.equals(obj);
    if (obj instanceof MyClass) return this.id.equals(((MyClass)obj).id);
    return false;
}

People seem to be hanging up the exact semantics of my method example above Let's try

public class MyWrapper<T extends A | B> {
    // my class can wrap A or B (unrelated classes). Yes I will probably use instanceof
}

Edit: at compile time I don't know what I might get (from external code), so I want to avoid every type having a specific class In addition, I must give my course a call to my class Method's external system, but another system can give me examples of various kinds, but a narrow and known variety

Some people commented on the example of "impure" One solution is to use the factory method to select my specific class according to the class of the incoming object, but the factory method must use instanceof, so you just move instanceof to another place - you still need instanceof

Or is this idea not a good idea?

Solution

Otherwise, there is no meaning unless all types have non - empty union types They are all implemented interfaces, or they are all extended base classes. In this case, you only need to specify the union type

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>