开发者

How to identify a class and an interface in the Java code?

Say suppose I have the following Java code.

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

How to find out whether the Person is a class or an interface?

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

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


If you don't already know whether Person is an interface or a class by nature of the documentation for the class/interface itself (you're using it, presumably you have some docs or something?), you can tell with code:

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

Details here.

Edit: Based on your comment, here's an off-the-cuff utility you can use:

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);
    }
}

Usage:

java CheckThingy Person


I think that in this case, you don't know because you shouldn't know. If you're writing something that extends or implements (the Employee class), then it's up to you to go look at the docs or the source code.

If, as in your example, you're just utilizing some classes/interfaces, you shouldn't need know or care if the Person class is concrete or abstract, or an interface, as long as it has a well defined API.


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

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

or

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

EDIT: On reading your comment to T.J. 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");


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

If you aren't using an IDE yet, I can recommend Eclipse or IntelliJ IDEA. If you're doing Java EE (JSP/Servlet and that kind of stuff), either grab Eclipse for Java EE or pay for IDEA Ultimate edition.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜