Generic OR instead of AND <T extends Number | CharSequence>

Is it possible to generically parameterize a method accepting EITHER ClassA OR InterfaceB ?

Does Not Compile Due to | Pseudocode

public <T extends Number | CharSequence> void orDoer(T someData){ // ... }

i.e. instead of writing multiple method signatures, I would like this one method to accept either a Number or CharSequence as an argument

Should Pass with a Number OR CharSequence argument

orDoer(new Integer(6));
int somePrimitive = 4;
orDoer(somePrimitive);
orDoer("a string of chars");

Answers


If you really want to do that, you'll need to wrap youur accepted classes inside a custom class of your own. In your example case, probably something like:

public class OrDoerElement {
    private final Number numberValue;
    private final CharSequence charSequenceValue;

    private OrDoerElement(Number number, CharSequence charSequence) {
        this.numberValue = number;
        this.charSequenceValue = charSequence;
    }

    public static OrDoerElement fromCharSequence(CharSequence value) {
        return new OrDoerElement(null, value);
    }

    public static OrDoerElement fromNumber(Number value) {
        return new OrDoerElement(value, null);
    }
}

And your orDoer method becomes:

public void orDoer(OrDoerElement someData) { .... }

Then you can build one of those and use in your method using either:

orDoer(OrDoerElement.fromCharSequence("a string of chars"));
orDoer(OrDoerElement.fromNumber(new Integer(6)));

But honestly, that sounds a bit too complex and too much work just to be able to call a method with different parameter types. Are you sure you can't achieve the same using two methods, and a third method for the common logic?


Need Your Help

C# combobox like dropdown list in web application

c# winforms combobox

I have comboBox component and i am adding items like comboBox1.Items.Add("Item1"). But i alo need to know some other info about this Item. So if i click "Item1" i need to get "102454".

AngularJS factory http returns empty

http angularjs factory angularjs-service

I'm trying AngularJS for the first time. I'm getting JSON data from a http-get request using a factory, but the object is returned empty, before the ajax-request is done.

WPF Controls: How to Reference Resources in Animations?

wpf wpf-controls styles storyboard

I have written a control and successfully created a storyboard to cause an animation during triggered events. It changes the fill of an ellipse for a duration of time. Instead of writing a new

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.