- Determine if a Class Implements an Interface in Java
- Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
- > CHECK OUT THE COURSE
- 1. Overview
- 2. Using Java Reflection API
- 2.1. The Data Model
- 2.2. The getInterfaces() Method
- 2.3. isAssignableFrom() Method
- 2.4. isInstance() Method
- 2.5. instanceOf() Method
- 3. Using Apache Commons Library
- 4. Using Reflections Library
- 5. Conclusion
- Java does class implement interface
- Java Interface
- Example
- Example
- Notes on Interfaces:
- Why And When To Use Interfaces?
- Multiple Interfaces
- Example
Determine if a Class Implements an Interface in Java
As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
> CHECK OUT THE COURSE
1. Overview
In this tutorial, we’ll take a look at several ways to determine if an object or a class implements a specific interface.
2. Using Java Reflection API
The Java Reflection API provides several ways to check whether an object or a class implements an interface. Using this API prevents adding a third-party library to our project.
2.1. The Data Model
The Java Runtime Environment(JRE) provides some ways to retrieve the implemented interfaces of a class.
First, let’s define a model with some interfaces and classes. For this example, we’ll define an interface MasterInterface and two sub-interfaces that extend the first one:
We’ll do the same for the classes with a first one implementing the MasterInterface and two subclasses implementing interfaces ChildInterface1 and ChildInterface2, respectively:
Here’s the code for our model:
public interface MasterInterface <> public interface ChildInterface1 extends MasterInterface <> public interface ChildInterface2 extends MasterInterface <> public class MasterClass implements MasterInterface <> public class ChildClass1 implements ChildInterface1 <> public class ChildClass2 implements ChildInterface2 <>
2.2. The getInterfaces() Method
The Java API provides a getInterfaces() on the Class object. This method retrieves the implemented interfaces of a Class. We can get all implemented interfaces of a class with this line of code:
List> interfaces = Arrays.asList(childClass2.getClass().getInterfaces()); assertEquals(1, interfaces.size()); assertTrue(interfaces.contains(ChildInterface2.class));
As we can see, this method only retrieves the directly implemented interfaces. Inheritance of the MasterInterface is not detected.
If we want to get a full inheritance tree, we’ll have to recurse over the implemented interfaces until we find the root interface:
static Set> getAllExtendedOrImplementedInterfacesRecursively(Class clazz) < Set> res = new HashSet>(); Class[] interfaces = clazz.getInterfaces(); if (interfaces.length > 0) < res.addAll(Arrays.asList(interfaces)); for (Classinterfaze : interfaces) < res.addAll(getAllExtendedOrImplementedInterfacesRecursively(interfaze)); >> return res; >
Then, after execution, we can check that we retrieved the MasterInterface in the Set:
assertTrue(interfaces.contains(ChildInterface2.class)); assertTrue(interfaces.contains(MasterInterface.class));
And now, we’re able to check if our object implements a specific interface in our model.
2.3. isAssignableFrom() Method
The previous method is quite verbose and painful, so the Java API provides a quicker way to check if an Object implements an interface. We can check this with the isAssignableFrom() method of the Class Object.
This method returns a true if the object inherits the specified interface, even if this isn’t a direct implementation:
ChildClass2 childClass2 = new ChildClass2(); assertTrue(MasterInterface.class.isAssignableFrom(childClass2.getClass()));
2.4. isInstance() Method
The Class object also provides an isInstance() method. This method returns true if the provided object implements the interface:
assertTrue(MasterInterface.class.isInstance(childClass2));
2.5. instanceOf() Method
The last way to check if an object implements an interface is to use the instanceOf operator. This operator also works with interfaces:
assertTrue(childClass2 instanceof MasterInterface);
3. Using Apache Commons Library
The Apache Commons Lang library provides utility classes for almost everything. The ClassUtils class is able to list all implemented interfaces of a class.
First of all, we need to add the Maven Central dependency to our pom.xml:
org.apache.commons commons-lang3 3.12.0
This is basically the same as the way we saw with the getInterfaces() method but we’ll only need one line of code :
List> allSuperInterfaces = ClassUtils.getAllInterfaces(childClass2.getClass());
This returns all implemented interfaces recursively:
assertTrue(allSuperInterfaces.contains(ChildInterface2.class)); assertTrue(allSuperInterfaces.contains(MasterInterface.class));
4. Using Reflections Library
The Reflections library is a third-party library that scans our objects and then allows us to run queries against the metadata collected.
We first need to add the Maven Central dependency to our pom.xml:
org.reflections reflections 0.10.2
The library needs to collect data before we can run our queries, so it needs to be initialized:
Reflections reflections = new Reflections("com.baeldung.checkInterface");
This operation scans the entire classpath provided and can take some time to complete. This may be done during the startup of our application so that future queries run smoothly.
Then, we can retrieve a list of interfaces implemented by a class:
Set> classes = reflections.get(ReflectionUtils.Interfaces.of(ChildClass2.class));
5. Conclusion
In this article, we saw different ways to check if a class implements a specific interface. Depending on the needs of our application, we can use standard Java Reflections API or rely on third-party libraries if we need more powerful functions.
As always, the complete code is available over on GitHub.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
Java does class implement interface
- Introduction to Java
- The complete History of Java Programming Language
- C++ vs Java vs Python
- How to Download and Install Java for 64 bit machine?
- Setting up the environment in Java
- How to Download and Install Eclipse on Windows?
- JDK in Java
- How JVM Works – JVM Architecture?
- Differences between JDK, JRE and JVM
- Just In Time Compiler
- Difference between JIT and JVM in Java
- Difference between Byte Code and Machine Code
- How is Java platform independent?
- Decision Making in Java (if, if-else, switch, break, continue, jump)
- Java if statement with Examples
- Java if-else
- Java if-else-if ladder with Examples
- Loops in Java
- For Loop in Java
- Java while loop with Examples
- Java do-while loop with Examples
- For-each loop in Java
- Continue Statement in Java
- Break statement in Java
- Usage of Break keyword in Java
- return keyword in Java
- Object Oriented Programming (OOPs) Concept in Java
- Why Java is not a purely Object-Oriented Language?
- Classes and Objects in Java
- Naming Conventions in Java
- Java Methods
- Access Modifiers in Java
- Java Constructors
- Four Main Object Oriented Programming Concepts of Java
- Inheritance in Java
- Abstraction in Java
- Encapsulation in Java
- Polymorphism in Java
- Interfaces in Java
- ‘this’ reference in Java
Java Interface
Another way to achieve abstraction in Java, is with interfaces.
An interface is a completely «abstract class» that is used to group related methods with empty bodies:
Example
// interface interface Animal < public void animalSound(); // interface method (does not have a body) public void run(); // interface method (does not have a body) >
To access the interface methods, the interface must be «implemented» (kinda like inherited) by another class with the implements keyword (instead of extends ). The body of the interface method is provided by the «implement» class:
Example
// Interface interface Animal < public void animalSound(); // interface method (does not have a body) public void sleep(); // interface method (does not have a body) >// Pig "implements" the Animal interface class Pig implements Animal < public void animalSound() < // The body of animalSound() is provided here System.out.println("The pig says: wee wee"); >public void sleep() < // The body of sleep() is provided here System.out.println("Zzz"); >> class Main < public static void main(String[] args) < Pig myPig = new Pig(); // Create a Pig object myPig.animalSound(); myPig.sleep(); >>
Notes on Interfaces:
- Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not possible to create an «Animal» object in the MyMainClass)
- Interface methods do not have a body — the body is provided by the «implement» class
- On implementation of an interface, you must override all of its methods
- Interface methods are by default abstract and public
- Interface attributes are by default public , static and final
- An interface cannot contain a constructor (as it cannot be used to create objects)
Why And When To Use Interfaces?
1) To achieve security — hide certain details and only show the important details of an object (interface).
2) Java does not support «multiple inheritance» (a class can only inherit from one superclass). However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma (see example below).
Multiple Interfaces
To implement multiple interfaces, separate them with a comma:
Example
interface FirstInterface < public void myMethod(); // interface method >interface SecondInterface < public void myOtherMethod(); // interface method >class DemoClass implements FirstInterface, SecondInterface < public void myMethod() < System.out.println("Some text.."); >public void myOtherMethod() < System.out.println("Some other text. "); >> class Main < public static void main(String[] args) < DemoClass myObj = new DemoClass(); myObj.myMethod(); myObj.myOtherMethod(); >>