java - How to identify if class has implemented marker interface -
i received question during interview, question
how identify if class has implemented marker interface
if there way find, how know marker interface implemented
determines interfaces implemented class or interface represented object.
if object represents class, return value array containing objects representing interfaces implemented class. order of interface objects in array corresponds order of interface names in implements clause of declaration of class represented object. example, given declaration:
class shimmer implements floorwax, desserttopping { ... }
suppose value of s instance of shimmer; value of expression:
s.getclass().getinterfaces()[0]
is class object represents interface floorwax; , value of:
s.getclass().getinterfaces()[1]
is class object represents interface desserttopping.
note approach not return true scenario instead superclass of shimmer
implements interfaces, example below:
public interface floorwax { } public interface deserttopping { } public class shimmer implements implements floorwax, desserttopping { } public class shimmerchild extends shimmer {} public static void main(string[] args) { // throws arrayoutofboundsexception system.out.println(new shimmerchild().getclass().getinterfaces()[0]); }
in case want below return interfaces, use approach described in @dylanmeeus answer class#isassignablefrom()
Comments
Post a Comment