Asif Rafiq
Asif Rafiq

Reputation: 291

Java Reflection

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

Upvotes: 0

Views: 385

Answers (3)

mtraut
mtraut

Reputation: 4740

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.

Upvotes: 1

Andreas Dolk
Andreas Dolk

Reputation: 114757

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.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533442

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.

Upvotes: 1

Related Questions