0

I need to find whether a class have implemented a specific interface(suppose java.io.Serializable)

following is my code

class Employee{},class Test implements java.io.Serializable{},class Point{},
class Main{}, class MyApp{},class TestApp implements java.io.Serializable{};

class MyMain
{
public static void main(String[] args)
{

String[] classes={"Employee","Test","Point","Main","MyApp"}; // array of class names in default package
Class interFace = Class.forName("java.io.Serializable");

for(int i=0 ;i < classes.length;i++) {

 Class clas = Class.forName(classes[i]);

 boolean match = !clas.isInterface() && !clas.isEnum() && interFace.isAssignableFrom(clas) ;

 if(match )
 {

 System.out.println(classes[i]+ "implements java.io.Serializable");

 }}}}

Output

Employee implements java.io.Serializable /// wrong

Test implements java.io.Serializable /// correct

Main implements java.io.Serializable /// wrong

TestApp implements java.io.Serializable /// correct

Problem

Problem is only with Employee and Main class when they are in default package.

I donot understand why this happen?

public class JarFileLoader extends URLClassLoader { 
  public JarFileLoader (URL[] urls) { 
    super (urls); 
  } 
  public void addFile (String path) throws MalformedURLException { 
    String urlPath = "jar:file:/" + path + "!/"; 
    addURL (new URL (urlPath)); 
  } 
}

class JarUtils { 
  public static List getClasseNamesInJAR(String jarName) throws Exception {
    ArrayList classes = new ArrayList();
    try { 
      JarInputStream jarFile = new JarInputStream(new FileInputStream(jarName)); 
      JarEntry jarEntry; 
      while (true) { 
        jarEntry = jarFile.getNextJarEntry(); 
        if (jarEntry == null) 
          break; 
        if (jarEntry.isDirectory()) 
          continue; 
        if ((jarEntry.getName().endsWith(".class"))) {
          classes.add(jarEntry.getName().replaceAll("/", "\\.")); 
        } 
      } 
      return classes; 
    } catch (Exception e) { 
      throw e; 
    } 
  } 
} 

public class ClassImplementer {
  private List getClasses(String path, String interfaceName) throws Exception {
    List list = new ArrayList();

    if (path.endsWith(".jar")) {

       List l = JarUtils.getClasseNamesInJAR(path);
        if(l!=null && l.size()<=0)
            return null;
        try {
            URL urls[] = {};
            JarFileLoader cl = new JarFileLoader(urls);
            cl.addFile(path);
            Class interFace = Class.forName(interfaceName);

            for (int i = 0; i < l.size(); i++) {

                String[] tempClass = l.get(i).toString().split(".class");
                Class clas = cl.loadClass(tempClass[0]);
                boolean match = !clas.isInterface() && !clas.isEnum() && interFace.isAssignableFrom(clas) ;
                if(match ) {
                    list.add(tempClass[0]);
                 }
            }
            return list;
        }
        catch (Exception ex) {
            throw ex;
        }
            return list;
    }
}

public class Test{
public static void main(String[] args)
ClassImplementer imp=new ClassImplementer();
try{
List l=imp.getClasses("c:/abc.jar","java.io.Serializable");
for(int i=0;i<l.size();i++)System.out.println(l.get(i)+" implements java.io.Serializable");
}catch(Exception ex){}
} 
5
  • 1
    Why are they in the default package? There is never a need to use the default package and it should be strictly avoided in all real code. Commented Jan 5, 2011 at 12:39
  • @skaffman - "Problem is only with Employee and Main class when they are in default package." Commented Jan 5, 2011 at 12:46
  • 2
    Tried to reproduce but with no success. The boolean expression works correct on my machine, regardless of the classes package. Commented Jan 5, 2011 at 12:57
  • @andreas_d Maybe i'm a little dumb. Did you manage to compile this stuff without change? So i believe the problem is somewhere in the parts omitted... Commented Jan 5, 2011 at 13:05
  • @mtraut - no, I just looked at the code an tested the condition. It resolves to false for any class that doesn't implement this interface. And the rest of this code can't be responsible for match becoming true for some strange conditions. Commented Jan 5, 2011 at 13:15

3 Answers 3

1

Your program does not match your output. When I correct for the errors in your code I get one output.

Testimplements java.io.Serializable

This appears to be correct to me for your program.

Sign up to request clarification or add additional context in comments.

Comments

1

Perhaps you provide complete, compilable source code (where do you catch exceptions ?) so one can spot the error in your code.

EDIT

I can spot nothing obvious. As everyone else has correct results - maybe you just work against an outdated "jar" file? delete and recreate with the current version of your test classes.

3 Comments

Just to expand on this: commas after class definition is a syntax error, TestApp is missing from your test String, exceptions are not handled, braces are unaligned and of course the real kicker - after correcting those issues the code works as intended.
@asif this is not helpful. Please edit the code in your question, perhaps by copying a compiled, error free piece of code from your editor and pasting here using source code formatting
@Asif Rafiq - please stop pasting code as a comment to this answer. Edit your question and add the code fragments like I did for your previous two comments (sorry for shouting, but mtraut already said this 20 minutes ago)
0

Assuming, the code you pasted to the comments is your actual code, then the problem is here:

(from class Inter)

for(int i=0;i<l.size();i++){
  String[] t=l.get(i).toString().split(".class");
  Class clas=cl.loadClass(t[0]);
  //                      ^^^^
  boolean m=!clas.isInterface()&&!clas.isEnum()&&iFace.isAssignableFrom(clas);
  if(m)
    list.add(t[0]);
  //         ^^^^
}

Replace t[0] with t[i] and check if the error is gone.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.