1

Given a package in java language, I want to know how many classes it contains and their list (list of these classes).

I can access to my package with myClass1.class.getPackage() but after this I don't have some thing like getClasses() or size() or lenght or ClassesCount().

Thank You

RiadSaadi
  • 391
  • 2
  • 7
  • 16

3 Answers3

1

In Java, classes are loaded dynamically. So there's simply no way to do what you're trying to do; the virtual machine itself does not know the full list of classes within a package.

Jose Torres
  • 347
  • 1
  • 3
  • but when I am programming and I write `myPackage.` just after writing point(.) I have the list of all classes but not when I write `myClass.class,getPackage()` – RiadSaadi Nov 23 '13 at 16:24
  • Right. Your development environment knows what all the classes are; it has to, because it needs to compile them. But this information is not available to the program itself unless you explicitly put it in. – Jose Torres Nov 23 '13 at 16:29
1

There are already many questions and answers on this, you can follow these links

a) How to get all classes names in a package?

b) How can I list all classes loaded in a specific class loader

c) Can you find all classes in a package using reflection?

Community
  • 1
  • 1
Santosh Joshi
  • 3,290
  • 5
  • 36
  • 49
  • I am sorry, I saw the first one and the second one they are not exactly like mine, but the last one is. what to do? should I delete the question? – RiadSaadi Nov 23 '13 at 16:29
  • @RiadSaadi I think you should not delete there are already many useful expert comments in this post. – Santosh Joshi Nov 23 '13 at 16:33
  • @SantoshJoshi As you know that this is a duplicate of other questions so you should not post as answer. –  Nov 23 '13 at 16:37
  • but in the reglementation, what to do in duplicate case? – RiadSaadi Nov 23 '13 at 16:41
  • @RiadSaadi, please, if you think that your question is a duplicate, go ahead and remove it. I am an answerer too, but I should not answer a question which has already complete answer somewhere else and better than mine. – Sage Nov 23 '13 at 16:41
  • @rocking, yes you are right, will take care of this. – Santosh Joshi Nov 23 '13 at 16:43
  • @SantoshJoshi There is a possibility of getting downvotes if you answer duplicate questions.So i just made you aware of it –  Nov 23 '13 at 16:45
1

Take a look at the reflections library which might allow to achieve this easily:

Reflections reflections = new Reflections("my.project.prefix");
Set<Class<? extends SomeType>> subTypes = 
           reflections.getSubTypesOf(SomeType.class);

I guess you can use Object in place of SomeType as Object is the super class of all the class in java:

 Set<Class<? extends Object>> allClasses = 
     reflections.getSubTypesOf(Object.class);
Sage
  • 15,290
  • 3
  • 33
  • 38