Is it possible to load a class by name if you don't know the whole package path? Something like:
getClassLoader().loadClass("Foo");
The class named "Foo" might be around, might not be - I don't know the package. I'd like to get a listing of matching classes and their packages (but not sure that's possible!),
Thanks
Nope. The Java ClassLoader.loadClass(String) method requires that class names must be fully qualified by their package and class name (aka "Binary name" in the Java Language Specification).
If you don't know the package, you don't know the name of a class (because it's part of the fully qualified class name) and therefore cannot find the class.
The Java class loading mechanism basically only allows you to do one thing: ask for a class with its fully qualified name, and the classloader will either return the class or nothing. That's it. There#s no way to ask for partial matches, or to list packages.
Contrary to the previous answers, and in addition to the answers in the question #reader_1000 linked to:
This is possible, by essentially duplicating the logic by which Java searches for classes to load, and looking at all the classfiles. Libraries are available that handle this part, I remember using Reflections. Matching classes by unqualified name isn't their major use case, but the library seems general enough and this should be doable if you poke around. Do note that this will, very likely, be a fairly slow operation.
Using java Reflections:
Class.forName(new Reflections("com.xyz", new SubTypesScanner(false)).getAllTypes().stream()
.filter(o -> o.endsWith(".Foo"))
.findFirst()
.orElse(null));
Even if you don't know the package name, sites like jarFinder might know it
Related
I am currently learning about Reflection and I have seen most of the similar posts to my question on stack however, I don't feel they fully answer my question on it.
I want to know if I have a package in Eclipse can I use Reflection to iterate through the classes in the package to find which one implements interface. There is only 1 interface so either they implement it or don't.
Could anyone provide a basic clear example as to how I may go about this? I have been told by some that this is just not possible whilst other people say it is possible using Reflection.
Thank you to any one who could help clear this matter.
Reflection API does not provide directly facility to iterate over classes in specific package. It concentrates on discovery of class once you have it.
To achieve what you want to have to read the class path of your application, iterate over the class path, open jars and go into directories, find files that end with *.class and get them as resource like getResource(full_class_name) or get it directly as class using Class.forName().
This method has a limitation: you will not see classes loaded by custom class loaders.
Unless this is an exercise I'd recommend you to use Reflections library that does everything you need and (probably) even more... :)
Some more details
Java system property "java.class.path" contains class path of your application separated with ; on Windows and : on Unix.
So, this is the way you can get list of class path elements:
System.getProperty("java.class.path").split(File.pathSeparator)
Here is some code sample that can help you to start:
for (String cpElement : System.getProperty("java.class.path").split(File.pathSeparator)) {
File cpFile = new File(cpElement);
if (!cpFile.exists()) {
continue;
}
if (cpFile.isDirectory()) {
findClassesInDirectory(cpFile);
} else {
findClassesInArchive(cpFile);
}
}
Etc, etc. I am leaving implementation of findClassesInDirectory() and findClassesInArchive() for you. Nice exercise. Have fun.
have you heard of guava-libraries for Java.
They provide useful utilities regarding reflection.
For your specific problem, I would have a look a the TypeToken and the method getTypes().
Good luck
yes you can so it. But with eclipse its more of an AST tree translation and not reflections. See if you want to iterate over source code and see which source file implements the interface you probably need AST tree walkers to do that. But on the other hand if you want to introspect at runtime the class files in a given package or a folder which implement the said interface then you need Reflections to do that. Either way its doable. I cant give you the code to try that out as a little time with Google will give you the answers you need though not all at the same place.
Reflection does not provide all operations for a total inspection.
For a known class one can get the physical URL of a class SomeClass using:
CodeSource codeSource = SomeClass.class.getProtectionDomain().getCodeSource();
if (codeSource == null) {
// Run-time class; URL into the rt.jar.
} else {
URL url = codeSource.getLocation();
// "file:/.... /classes/.../SomeClass.class"
// "jar:file:/... /someJar.jar!/.../SomeClass.class"
}
For Java run time classes (rt.jar) codeSource will be null.
On the URL of the jar you can open a (zip) file system, and walk through folders as any real file system.
You'll probably want to inspect classes without $ in the name (embedded, generated anonymous classes): only fileName.matches("[^$]+\\.class").
I've seen lots of examples like com.mycompany.someapp. Seems to be the reverse of the domain. Which actually makes sense to me.
But at the end of the day, does it really matter? We are a small shop so maybe we don't see the benefits of proper domain naming.
So, is it good practice to name it to match the domain? If so, why?
Extracted from the link to Naming a Package (Java Tutorial) in Andrew's comment: (I claim no originality or ownership of the following).
Naming a Package
With programmers worldwide writing classes and interfaces using the Java programming language, it is likely that many programmers will use the same name for different types. In fact, the previous example does just that: It defines a Rectangle class when there is already a Rectangle class in the java.awt package. Still, the compiler allows both classes to have the same name if they are in different packages. The fully qualified name of each Rectangle class includes the package name. That is, the fully qualified name of the Rectangle class in the graphics package is graphics.Rectangle, and the fully qualified name of the Rectangle class in the java.awt package is java.awt.Rectangle.
This works well unless two independent programmers use the same name for their packages. What prevents this problem?
Naming Conventions
Package names are written in all lower case to avoid conflict with the names of classes or interfaces.
Companies use [their] reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com.
Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name (for example, com.example.region.mypackage).
Packages in the Java language itself begin with java. or javax.
In some cases, the internet domain name may not be a valid package name. This can occur if the domain name contains a hyphen or other special character, if the package name begins with a digit or other character that is illegal to use as the beginning of a Java name, or if the package name contains a reserved Java keyword, such as "int". In this event, the suggested convention is to add an underscore. For example:
Legalizing Package Names Domain Name Package Name Prefix
hyphenated-name.example.org org.example.hyphenated_name
example.int int_.example
123name.example.com com.example._123name
Happy coding.
Matching the domain gives you greater confidence against name collisions. It's probably more important to designers of 3rd party libraries than you and your app.
Yes, that's the suggested convention in the Java Language Specification, section 7.7.
If unique package names are not used, then package name conflicts may arise far from the point of creation of either of the conflicting packages. This may create a situation that is difficult or impossible for the user or programmer to resolve. The class ClassLoader can be used to isolate packages with the same name from each other in those cases where the packages will have constrained interactions, but not in a way that is transparent to a naïve program.
You form a unique package name by first having (or belonging to an organization that has) an Internet domain name, such as sun.com. You then reverse this name, component by component, to obtain, in this example, com.sun, and use this as a prefix for your package names, using a convention developed within your organization to further administer package names.
You don't have to follow the convention, but it's generally considered good practice. After all, suppose at some point in the future you want to release some of your code as open source - but you want to avoid naming collisions. At that point, you really ought to follow the same conventions as everyone else - and as it doesn't hurt to do so from the start...
The idea behind using domain name is to avoid namespace collisions in packaging. This only works if everyone follows the convention. So, yes, the convention is important. That said, if you never plan on exporting your code as an API or providing it to a third party, it's likely there is little downside to using whatever package name you feel like.
Practically speaking I like it for a number of reasons:
It gives users an easy place to go to just from looking at the package name
It avoids collisions between packet names (i.e. two "media" packages could be very likely otherwise)
It helps identify the same author over separate pieces of software
It keeps package names roughly the same length (ok, this is just an aesthetic point but I like it!)
As well as this, it's also recommended in the JLS. It's not a requirement, but when it's practically 0 effort to do, I'd do it unless there's a good reason otherwise.
Perhaps a better question to ask is why don't you want to follow that convention? If there's no real reason, there's no harm in following it!
The main aim is to guarantee uniqueness of package names, but if you're never going to release code for others to use then it probably doesn't matter, but there is a lot to be said for sticking with convention and worrying about the stuff that does matter. Otherwise come the day that you realise you have a great library that you want to share you could be kicking yourself for going against the flow.
Yes, it is sensible to always use a naming scheme. As a counter-example, assume that everyone would use the default package for their classes.
Common classes like User or Address would be used by several libraries, but in the end there can be only one class of a certain name in the runtime environment. (loosely speaking, it is not completely correct.)
In big projects you will likely use many external libraries, like Apache Commons, Google Guava, Spring, Hibernate, Terracotta. It's good that these libraries all use their own namespace, so that their internal classes do not accidentally conflict.
i often have in java projects a lot of small helper("storage") classes like
2-Tuple, 3-Tuple, Point, .. (think you know what i mean)
Classes that mostly only have class variables, a constructor and getters/setters.
And in my current project, i wanted to store those small classes, that are often used in a lot of other classes in the project in a seperate package. But i do not really know how to name it (my motherlanguage is not english, but code should be for english readers.)
Hope you can give me an answer on this little questions.
Greetings
:)
Different people would name these differently as the names are a matter of personal choice.
A few options:
If the storage classes conform to the Javabeans conventions, you could add the suffix "Bean" eg PointBean
I have also seen a suffix of "DO" or "VO" being used to denote a "data object" or "value object". eg PointDO
You could leave the class name as is eg Point. However if you feel that it does not convey the fact it is a storage class, try to make the package name convey that fact eg
com.xyz.valueobjects.Point
or
com.xyz.dataobjects.Point
or
com.xyz.storage.Point
Personally I like to use style #3.
I'd stick those kinds of classes in a *.util package.
I'd go with something like:
utils or the more verbose utilities
you can then break that down further if you need to:
utils.data for data-related utility classes, for example.
Additionally, there's a question here on whether to pluralise or not: Naming convention for utility classes in Java
For your information the "storage classes" you are referring to are called Java Beans. Using the popular model view controller design pattern; these would be your model. So lets say you want to put them in a package called model and the domain name of your company is mycompany.com, then the propper java naming convention would be com.mycompany.model; add this line as the first line of code (before any import statements) to all of your Java bean classes:
package com.mycompany.model;
You must also move your Java bean files into a folder structure that is the same. Lets say the file with your main method is in the directory /%ProjectHome%/, then your Java Beans go in a folder /%ProjectHome%/com/mycompany/model/
To compile these files you will now have to change to your /%ProjectHome%/ directory then type javac com/mycompany/model/*.java
Then you will be able to import these files from your other java classes by typing
import com.mycompany.model.*;
Also note, that the Java convention for package names is all lower case, as not to clash with the name space of Class names.
Hope this helps.
I believe what you're doing is using objects purely for storing data (no behaviour). And since you're talking about tuples, I assume these are used for transferring data to/from your database, so perhaps just "data objects"?
This is language agnostic, but I'm working with Java currently.
I have a class Odp that does stuff. It has two private helper methods, one of which determines the max value in an int[][], and the other returns the occurrences of a character in a String.
These aren't directly related to the task at hand, and seem like they could be reused in future projects. Where is the best place to put this code?
Make it public -- bad, because Odp's functionality is not directly related, and these private methods are an implementation detail that don't need to be in the public interface.
Move them to a different class -- but what would this class be called? MiscFunctionsWithNoOtherHome? There's no unifying theme to them.
Leave it private and copy/paste into other classes if necessary -- BAD
What else could I do?
Here's one solution:
Move the method that determines te max value in a two-dimensional int array to a public class called IntUtils and put the class to a util package.
Put the method that returns the occurrences of a character in a String to a puclic class called StringUtils and put the class to a util package.
There's nothing particularly bad about writing static helper classes in Java. But make sure that you don't reinvent the wheel; the methods that you just described might already be in some OS library, like Jakarta Commons.
Wait until you need it!
Your classes wil be better for it, as you have no idea for now how your exact future needs will be.
When you are ready, in Eclipse "Extract Method".
EDIT: I have found that test driven development give code that is easier to reuse because you think of the API up front.
A lot of people create a Utility class with a lot of such methods declared as static. Some people don't like this approach but I think it strikes a balance between design, code reuse, and practicality.
If it were me, I'd either:
create one or more Helper classes that contained the methods as static publics, naming them as precisely as possible, or
if these methods are all going to be used by classes of basically the same type, I'd create an abstract base class that includes these as protected methods.
Most of the time I end up going with 1, although the helper methods I write are usually a little more specific than the ones you've mentioned, so it's easier to come up with a class name.
I not know what the other languages do but I have the voice of experience in Java on this: Just move to the end-brace of your class and write what you need ( or nested class if you prefer as that is accepted canonical convention in Java )
Move the file scope class ( default access class right there in the file ) to it's own compilation unit ( public class in it's own file ) when the compiler moans about it.
See other's comments about nested classes of same name if differing classes have the same functionality in nested class of same name. What will happen on larger code bases is the two will diverge over time and create maintainability issues that yield to Java's Name of class as type of class typing convention that forces you to resolve the issue somehow.
What else could I do?
Be careful not to yield to beginner impulses on this. Your 1-2 punch nails it, resist temptation.
In my experience, most large projects will have some files for "general" functions, which are usually all sorts of helper functions like this one which don't have any builtin language library.
In your case, I'd create a new folder (new package for Java) called "General", then create a file to group together functions (for Java, this will just be a class with lots of static members).
For example, in your case, I'd have something like: General/ArrayUtils.java, and in that I'd throw your function and any other function you need.
Don't worry that for now this is making a new class (and package) for only one function. Like you said in the question, this will be something you'll use for the next project, and the next. Over time, this "General" package will start to grow all sorts of really great helper classes, like MathUtils, StringUtils, etc. which you can easily copy to every project you work on.
You should avoid helper classes if you can, since it creates redundant dependencies. Instead, if the classes using the helper methods are of the same type (as kbrasee wrote), create an abstract superclass containing the methods.
If you do choose to make a separate class do consider making it package local, or at least the methods, since it may not make sense for smaller projects. If your helper methods are something you will use between projects, then a library-like approach is the nicest to code in, as mentioned by Edan Maor.
You could make a separate project called utils or something, where you add the classes needed, and attach them as a library to the project you are working on. Then you can easily make inter-project library updates/fixes by one modification. You could make a package for these tools, even though they may not be that unified (java.util anyone?).
Option 2 is probably your best bet in Java, despite being unsatisfying. Java is unsatisfying, so no surprise there.
Another option might be to use the C Preprocessor as a part of your build process. You could put some private static functions into file with no class, and then include that file somewhere inside a class you want to use it in. This may have an effect on the size of your class files if you go overboard with it, of course.
I'd like to define an interface called Tag in a Java package I am working on, but am hesitant to use such an ordinary-sounding name because of the collision issue. (e.g. you can import only one class or interface with a particular name; if there are more than one that share the same name, you can use import for one of them, but the rest you have to explicitly refer to with the entire package name e.g. com.yoyodyne.games.outdoors.Tag)
I also don't really have a more detailed name for it (it's supposed to represent a tag like the tags in StackOverflow posts or other online websites); the closest I can think of is maybe TaxonomyTag.
Are there strategies for dealing with this? The only one I can think of is to define a static class (like Collections) that contains a public interface Tag, e.g. if I call it Taxonomy then I can import Taxonomy and refer to Tag as Taxonomy.Tag -- but that doesn't sound much more helpful.
edit: one widely-known example of this collision is ca.odell.glazedlists.matchers.Matcher and java.util.regex.Matcher which is a pain if you are trying to use regular expressions with the GlazedLists library.
I don't see a problem with naming the class Tag. Your package name makes it universally unique and that is one of the purposes of packages - to resolve naming conflicts.
Even within the Java API there are multiple classes with the same name: java.util.Date, java.sql.Date for example. If you need both in your code then use the fully qualified name.
How many people are going to be using this class? If it's meant to be a general purpose library, I would go with a less-generic name to avoid collisions. If it's just you, and you really don't bite the bullet and go with fully-qualified names for now.
If it becomes a problem before you release the package, just refactor it to a new name.
In similar situations I have found some alternate name for short class names because I hate using FQNs. Even something like JasonSTag can work as a temporary fix; just don't release it that way. Often halfway through implementation I'll find a better way to describe the class, something more descriptive than "Tag".
Are you being lazy? If your class is using imports such that "Tag" could be misconstrued by someone reading your code, even momentarily, then it is worthwhile to think of a better name, despite the package naming convention. Don't underestimate the power of naming---or renaming as the class changes.
I wouldn't really be concerned with this.
What you should be concerned with is how well your class/interface name matches what the piece of code actually does. If Tag succinctly describes what the class/interface does and/or is meant to model, then I think it is a great name.
I can't really see the situation where you'd be using this Tag type in the same class along with other Tag types declared in different packages. But, if you have to, then it's not really that much of a pain to refer to the other Tag types by their fully qualified name.
I believe that how well you named something is greater than making things convenient.
The best strategy is to write classes which do one thing well. These classes do need the minimum of imports, so you have the reduction of import statements.
I looked for standard Tag interfaces; found one in java.swing..html, another one deep in servlet API, and another in tapestry library. I am sure that your class should not directly use one of these (or similar APIs), so you may not be afraid of namespace pollution.
Other solution is to prefix tag with the object it will be used on. E.g. ArticleTag. But you must carefully choose the object name. Or, anyway, you can always refactor it later.
Generally the number of conflicts, even with "ordinary" sounding names, is low. I'd chose a meaningful name within the context of the package.
Do not do somethiong "silly" like prefix it with the company name, eg: YoYoDyneTag.
It has gone out of style to use adjectives/adverbs as interface names recently, however, in your case it wouldn't sound that bad if you used 'Tagable' or 'TaxonomyTagable'.
This only tend to be a problem if you need to use more than one class with the same name in a single class. Examples: java.awt.List and java.util.List, java.util.Date and java.sql.Date.
If you stay away from those already used in the standard Java runtime you will most likely not have a problem.
Whatever you do - make the name you choose a good and descriptive one - this goes especially for those in a public API. You will live with them forever.