0

Have got two projects javaapplication2 and javaapplication1. The same being their package names. In javaapplication2 ive imported javaapplication1 using

import javaapplication1.*;

i need to list all classses in the packeage. How to achieve this? I tried a simple code but it gets a null exception.

Package pck;
pck = Package.getPackage("javaapplication1");
System.out.println(pck.getClass());
cooltoad
  • 171
  • 2
  • 12

3 Answers3

0

I guess the jar containing package javaapplication1 is not in classpath as

  Package.getPackage("javaapplication1");

is returning null for you.

Also,

You can have a look at the following link:

http://dzone.com/snippets/get-all-classes-within-package

or can explore the Reflection library from Google in order to get the required information, below is a sample code.

e.g.

Reflections reflections = new Reflections("javaapplication1");
Set<Class<? extends Object>> allClasses = reflections.getSubTypesOf(Object.class);
Himanshu Bhardwaj
  • 4,038
  • 3
  • 17
  • 36
0

I don't have enough rep to comment on this question or to mark it as such, but it is a duplicate of:

Getting all Classes from a Package

There are many good answers listed on that question - for instance the top is looking for classes that implement ICommand, so to implement this all you need to do is remove:

if (ICommand.class.isAssignableFrom(cls)) {
  commands.add((Class<ICommand>) cls);
}

from the for loop and you have what you want.

Community
  • 1
  • 1
Rossiar
  • 2,416
  • 2
  • 23
  • 32
  • You are right but secondly i also need to retrieve the method names from corresponding classes. Dont think this way would be able to make me do that. – cooltoad May 15 '13 at 10:41
  • The http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Class.html documentation for Java says you can use getDeclaredMethods() to retrieve a list of Method objects from a Class. – Rossiar May 15 '13 at 10:46
0

If you go throgh the object class API it is written as:

//Object API


getClass public final Class getClass()Returns the runtime class of an object. That Class object is the object that is locked by static synchronized methods of the represented class.

Returns: the object of type Class that represents the runtime class of the object.


It's clearly written as it represents the run time class of an object. Suppose if you have class called as "Helloworld" in side "javaapplication1" package create object of the class as:

Helloworld world=new Helloworld(); and then try to run as System.out.println(wolrld.getClass()); It will return the class path of current object.

NullPointer
  • 152
  • 1
  • 16