How to define class and interface in Java code?

Let's say I have the following Java code.

public class Example { public static void main(String[] args){ Person person = new Employee(); } } 

How to find out if a person is a class or an interface?

Because the Employee class can extend it if it is a class, or implement it if it is an interface.

And in both cases Person person = new Employee (); .

+6
java
source share
4 answers

If you still do not know if Person interface or a class by the nature of the documentation for the class / interface itself (do you use it, presumably, do you have any documents or something else?), You can tell with the code:

 if (Person.class.isInterface()) { // It an interface } 

More details here .

Change Based on your comment, you can use the off-the-muff utility here:

 public class CheckThingy { public static final void main(String[] params) { String name; Class c; if (params.length < 1) { System.out.println("Please give a class/interface name"); System.exit(1); } name = params[0]; try { c = Class.forName(name); System.out.println(name + " is " + (c.isInterface() ? "an interface." : "a class.")); } catch (ClassNotFoundException e) { System.out.println(name + " not found in the classpath."); } System.exit(0); } } 

Using:

 java CheckThingy Person 
+9
source share

I think that in this case you do not know, because you should not know. If you are writing something that is being expanded or implemented (the Employee class), then you need to look at the documents or the source code.

If, as in your example, you just use some classes / interfaces, you do not need to know or care if the Person class is concrete or abstract or an interface if it has a well-defined API.

+5
source share

For this, you can use the isInterface() method of the Class class. What is your reason for this? You have a poorly documented library, where do you need to find out? Perhaps if we knew what you were trying to do, a more elegant solution might be proposed.

 if(Class.forName("Person").isInterface()) //do interface stuff else //do class stuff 

or

 if(Person.class.isInterface()) ... 

EDIT: after reading your comment on TJ Crowder's answer. This is what I would do:

 if(Person.class.isInterface()) System.out.println("Person is an Interface"); else System.out.println("Person is a class"); 
+2
source share

Just do Ctrl + leftclick on Person in your IDE and / or read its source and / or javadoc.

If you are not using an IDE yet, I can recommend Eclipse or IntelliJ IDEA . If you are doing Java EE (JSP / Servlet and such things), either grab Eclipse for Java EE or pay for the IDEA Final Release .

+2
source share

All Articles