-2

I'm trying to rewrite some very old C# (.Net 2.0) code of mine into Java. Program is simple but i stumbled upon this part which i have no idea how to transfer into java:

public ISomething listContainsType(Type typeToCheck) {
        foreach(ISomething obj in _List)
            if (obj.GetType() == typeToCheck)
                return obj;

        return null;
    }

So, code above goes through list knowing only that each element implements "ISomething" and checks which class actually implements said interface. At least, that how it worked with .Net 2.0.

What would be Java equivalent of code above?

I know that above lines give that "code smell" but before refactoring i would like to rewrite it "as is" so i can test final product using the same testing methods.

guest86
  • 2,894
  • 8
  • 49
  • 72

2 Answers2

0

Java's equivalent of Type is Class. Other than that, it's basically the same:

public ISomething listContainsType(Class<?> typeToCheck) {
    for (ISomething obj : _List)
        if (obj.getClass() == typeToCheck)
            return obj;
    return null;
}

You would call it like this:

ISomething s = listContainsType(SomeType.class);
shmosel
  • 49,289
  • 6
  • 73
  • 138
0

For the sake of exercise, I've tried implementing something along the lines of:

static public ISomething listContainsType(Class<?> typeToCheck) {
    for (ISomething obj : _List) 
         if (Arrays.stream(obj.getClass().getInterfaces()).anyMatch(typeToCheck::equals))
        return obj;

    return null;
}

Call it like this: listContainsType (Serializable.class).

EDIT: @shmosel's code tests whether class is of a given type. My code tests whether it implements a given interface. Whichever version you want depends on your needs. Check this question for implementation of code that looks at all the interfaces that a class (directly or indirectly) implements.

Community
  • 1
  • 1
lukeg
  • 4,189
  • 3
  • 19
  • 40