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

use class#getinterfaces():

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

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -