Technically speaking, you CAN use instanceof to check if an object is a certain type.
However... That's NOT a good idea.
The way you've declared your method, it can accept a List of any type, so it isn't necessarily going to be A or B.
It's hard to tell what you're trying to do, but you probably should make your method generic.
You can do so like this:
public static <T> String method(List<T> arg) {
// We now know that the type of the list is T, which is
// determined based on the type of list passed to this
// method. This would demonstrate the point better if
// the return type was T, but I'm leaving the return type
// as String, because that's what your code returns.
}
Here's a better example:
If you want to create a generic method that returns the first element of a list, you would do it like this:
public static <T> T firstElement(List<T> theList) {
if (theList == null) {
return null;
}
T objectOfTypeT = theList.get(0);
return objectOfTypeT;
}
Note that the return type is now T.
Because we made this method generic, it can return the same type that is used in the List.
You would typically just return theList.get(0), but I added a line to make the purpose of generics more obvious.
Explanation of syntax:
The <T> indicates that this method takes one type parameter named T.
The T that immediately follows is the return type (just like you would normally return String, Integer, etc...).
The T in the List parameter is how the compiler knows what the heck a T is.
This allows the compiler to say: "This method expects something of type T. Oh look... The list is also of type T. If somebody passes a list of Strings to this method, than T must be a String. If somebody passes a list of Integers to this method, T must be an Integer."
In contrast, your method can only return a String and it has no idea what type is used in the List.
Also...
If A and B both extend the same class, named TheParentClass, you could declare your method like this:
public static String method(List<? extends TheParentClass> arg)
That way, you'd know a little more about the possible types of your parameter (and can benefit from compile time type checking).