You can not.
Or otherwise, any array and any reference already satisfies your requirement "an array of type x and another variable with the same type as the array", because any array is an "array of type Object " and any reference of the same type ( Object ).
What you want is not intended for security purposes. Think, hypothetically, that there is a language function to do what you want. It can only work with types of argument expressions at compile time. But someone can always do this:
Object[] foo = anyArrayExpression; Object bar = anyReferenceExpression; arrayContains(foo, bar);
or
arrayContains((Object[])anyArrayExpression, (Object)anyReferenceExpression);
(And by the way, none of them does anything suspicious or unsafe. An adult is always 100% safe and legal in Java.)
Thus, any array and any reference can always be passed to your function in any case, and your function should always process the actual objects like any type of array and any type object in any case. Thus, your function does not achieve anything.
Even if you restrict it to subtypes of some type X , and your function accepts only X[] and X , it may always be that the actual runtime class of the objects referenced in is Y[] and Z , where Y and Z are unrelated subtypes of X This is just a fact of how a system like Java works. That way, your function will always deal with the type of runtime component that is potentially not related to the runtime class of another object, no matter how you do it. (The only exception would be if X was final, so it has no subclasses, but then your restriction would be pointless, because it would be trivial always true.)
source share