0

I trying to find out jar name for using class name . Assume I having class Name as "Socket" or " LinkedList" as String. So I want know how to find out , which jar it's belong',s. I am trying to find out by this way

 public static String getModuleName(Class classname) {
    String modulename = null;
    URL resource = classname.getResource('/' + classname.getName().replace('.', '/') + ".class");
    System.out.println(resource.getPath());
    String[] split = resource.getFile().split("/");
    for (String string : split) {
        if (string.contains("jar")) {
            modulename = string.replace("!", "");
        }
    }
    return modulename;

}

In this method If I am passing

    Class class1 = String.class;
    System.out.println(getModuleName(class1));

It's Giving Jar name but it's giving jar name but for some requirement , I don't have like "String.class" but Only string "String" . From this string how ton find out which jar it's belongs.

Thanks

Pankaj Kumar
  • 151
  • 1
  • 3
  • 9
  • maybe Class.forName("java.lang.String") ? so u got the Class instance and then can use it to get the jar name – Sergi Sep 15 '16 at 12:19
  • I used same process but it's giving result with the help of "String.class" but I want from string ? – Pankaj Kumar Sep 15 '16 at 13:33

1 Answers1

0

What you can do is take the string input and then add .class to it and them use Class.forName for converting it to class object (fully qualified name).

String classstring = oldstring + ".class";
Class<?> class1 = Class.forName(classstring);
System.out.println(getModuleName(class1));

Or

String classstring = oldstring;
ClassLoader cloader;
Class class2 = cloader.loadClass(classstring);
System.out.println(getModuleName(class2);
Techidiot
  • 1,921
  • 1
  • 15
  • 28