How to make Class.forName ignore lowercase/uppercase - java

For example when I have a class named;
'MonkeyBusiness'
I know I can call it using Class.forName("MonkeyBusiness");
But when I call it using Class.forName("monkeyBusiness"); or Class.forName("monkeybusiness");
it gives me the exception;
Exception in thread "main" java.lang.NoClassDefFoundError: monkeyBusiness
(wrong name: ntx/gmd/services/usage/MonkeyBusiness)
Is it possible to call it using any case-formatted string? If so, how?

You don't.
Monkey monkey and MONKEY are three totaly different things in Java.
Why do you need such a function? The root problem might be that you don't know which classes are relevant within your application.
There are two things you can do. First, have an internal convention that you only use lowercase or CamelCase class names. In this way, just convert your search to the appropriate format: Class.forName(className.toLowerCase())
Secondly, you can make a cache of all used classes, and look the appropriate name up from cache. Just make a list with the lowercase name as the key, and the real name as the value.
Thirdly, but not recommended, brute force check all combinations. But this creates an awfully bad scaling function for longer names: 2^n, for n-length names.

You can write a ClassLoader that ignores case. Java ClassLoaders basically only support one function: a client can say "Here's a String, please load the class with that name", and the ClassLoader either replies "Sorry, I don't know the class", or "Yes, here is the class". How the ClassLoader implements this behavior is complete up to its implementer.

Related

How to detect java local variables by an interface type and then find methods called on them?

I have some (maybe) strange requirements - I wanted to detect definitions of local (method) variables of a given interface name. When finding such a variable I would like to detect which methods (set/get*) will be called on this variable.
I tried Javassist without luck, and now I have a deeper look into ASM, but not sure if it is possible what I wanted.
The reason for this is that I like to generated a dependency graph with GraphViz of beans that depend on the same data structure.
If this thing is possible could somebody please give me a hint on how it could be done? Maybe there are other Frameworks that could do?
01.09.2015
To make things more clear:
The interface is self written - the target of the whole action is to create a dependency graph in the first step automatically - later on a graphical editor should be implemented that is based on the dependencies.
I wonder how FindBugs/PMD work, because they also use the byte code and detect for example null pointer calls (variable not initialized and method will be called on it). So I thought that I could implement my idea in the same way. The whole code is Spring based - maybe this opens another solution to the point? Last but not least I could work on a source-jar?
While thinging about the problem - would it be possible via ASM/javassist to detect all available methods from the interface and find calls to them in the other classes?
I’m afraid, what you want to do is not possible. In compiled Java code, there are no local variables in the form you have in the source code. Methods use stack frames which have memory reserved for local variables, which is addressed by a numerical index. The type is implied by what instructions write to it and may change throughout the method’s code as the memory may get reused for different variables having a disjunct scope. The names on the other hand are completely irrelevant.
When bytecode gets verified, the effect of all instructions to the stack frame will get modeled to infer the type of each stack frame slot at each point of the execution so that the validity of all operations can be checked. Starting with class file version 50, there will be StackMapTable attributes aiding the process by containing explicit type information, but only for code with branches. For sequential code, the type of variables still has to be derived by inference.
These inferred types are not necessarily the declared types. E.g., on the byte code level, there will be no difference between
CharSequence cs="foo";
cs.charAt(0);
and
String s="foo";
((CharSequence)s).charAt(0);
In both cases, there will be a storage of a String constant into a local variable followed by the invocation of an interface method. The inferred type will be String in both cases and the invocation of a CharSequence method considered valid as String implements CharSequence.
This disproves the idea of detecting that there is a local variable declared using the CharSequence (interface) type, as the actual declared type is irrelevant and not stored in the regular byte code.
There are, however, debugging attributes containing information about the local variables, see the LocalVariableTable attribute and libraries like ASM will tell you about the declarations if such information is present. But you can’t rely on these optional information. E.g. Oracle’s JRE libraries are by default shipped without them.
I don't sure I understood exacly what you want but .
you can use implement on each object ,
evry object that have getter you can implement it with class called getable .
and then you could do stuff only on object that have the function that you implement from the class getable .
https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html

Why does Java allow us to compile a class with a name different than the file name?

I have a file Test.java and the following code inside it.
public class Abcd
{
//some code here
}
Now the class does not compile, but when I remove the public modifier , it compiles fine.
What is the reasoning behind Java allowing us to compile a class name that is different from the file name when it is not public.
I know it is a newbie question, but I'm not able to find a good explanation.
The rationale is to allow more than one top-level class per .java file.
Many classes—such as event listeners—are of local use only and the earliest versions of Java did not support nested classes. Without this relaxation of the "filename = class name" rule, each and every such class would have required its own file, with the unavoidable result of endless proliferation of small .java files and the scattering of tightly coupled code.
As soon as Java introduced nested classes, the importance of this rule waned significantly. Today you can go through many hundreds of Java files, never chancing upon one which takes advantage of it.
The reason is the same as for the door plates. If some person officially resides in the office (declared public) his/her name must be on the door tag. Like "Alex Jones" or "Detective Colombo". If somebody just visits the room, talks to an official or cleans the floor, their name does not have to be officially put on the door. Instead, the door can read "Utilities" or "Meeting room".
The Java specification states you can only have at most one public class per file. In this case, the class name should match the file name. All non-public classes are allowed to have any name, regardless of the file name.
I think allowing them is a prerequisite for nested classes. Anonymous Classes in particular dramatically reduce the number of .java files required. Without support for this, you would need lots of single method interface implementations in their own separate files from the main class they are used in. (I'm thinking of action listeners in particular)
There is a good explanation of all nested classes in the Nested Classes Java tutorial on Oracle's website, which has examples of each. It also has a reason they are useful, which I'll quote:
Why Use Nested Classes?
Compelling reasons for using nested classes include the following:
It is a way of logically grouping classes that are only used in one place: If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.
It increases encapsulation: Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be
declared private. By hiding class B within class A, A's members can be
declared private and B can access them. In addition, B itself can be
hidden from the outside world.
It can lead to more readable and maintainable code: Nesting small classes within top-level classes places the code closer to where it is
used.
(emphasis mine)
I am not familiar with Java spec back in the early days, but a quick search shows inner classes were added in Java 1.1.
I look at it the other way round. The natural state of affairs would be for the programmer to pick both the class name and the file name independently. Probably in order to simplify finding public classes from outside a package during compilation, there is a special restriction that a public class be in a file with the corresponding name.
Note that Java is case-sensitive, but the filesystem need not be. If the file's base name is "abcd", but the class is "Abcd", would that conform to the rule on a case-insensitive filesystem? Certainly not when ported to a case-sensitive one.
Or suppose you happened to have a class called ABCD, and a class Abcd (let's not get into that being a bad idea: it could happen) and the program is ported to a case insensitive filesystem. Now you not only have to rename files, but also classes, oops!
Or what if there is no file? Suppose you have a Java compiler which can take input on standard input. So then the class has to be named "StandardInput"?
If you rationally explore the implications of requiring file names to follow class names, you will find that it's a bad idea in more than one way.
Also one other point that many answers missed to point out is that without the public declaration, the JVM would never know which classes' main method needs to be invoked. All classes declared in one .java file can all have main methods, but the main method is run on only the class marked as public. HTH
Because of a java file can contains more than one class, it may have two classes in one java file. But a java file have to contain a class as the same name as file name if it contains a public class.

True java generics (templates)

After taking a look in the Java VM specification, I noticed that a lot more than just ASCII letters could be used to create an identifier.
Firstly, I was wondering if there were any extra symbols (apart from $, that are available for identifiers)
Do you think it would be possible, with the extended character set to encode additional information in an identifier, and a custom classloader, to implement true Java generics?
Of course, you would have to get around type erasure, but that could be possible with a custom parser?
So you could store generic names in a format like: $g$GenericList$_Java_lang_String$
I'm using GenericList here as I don't intend to modify the original implementation!
Load them in with the class loader, create a proper GenericList<String> version and send it back.
EDIT: I plan to use this for a language I'm building on the JVM. As it uses $'s and _'s as special characters, encoding information like that might just work!
EDIT 2: I suppose the more difficult thing to do would be generic methods? Does anyone have any information on how those would be implemented?
EDIT 3: Since classes can only be unloaded when the classloader disappears, would I be able to cache and remove resolved templates like it works in .Net, or would I do it like C++?
The JVM allows any characters in class/field/method names except /, and ; which have a special meaning. Using numbers and other character is common for obfuscators to make de-compiling difficult.
However you could just use the $ and _ for generated class/fields/methods.
Note: JDK 7 is supposed to have better generic support with the Type with a combination of Class and generics.
EDIT:
One way to have proper generic type is to always use
Set<String> set = new LinkedHashSet<String>() { };
The use of { } creates an anonymous class which has a parent type with the generic you want. You can get this information via reflection.
You can cache and remove class by having your own class loader which you dispose of as you wish. The most extreme case would be to have a ClassLoader per class.
Once you have your own Generic types, you could just use these in your methods, like normal types.
As you can use Unicode you can basically use everything except the few letters mentioned in the previous answer (/,;).
There is nothign like "true generics" btw ... I know what you mean ;D and that is called "Templates".
Yes you can use any unicode character as identifier name in java. See here for identifier names allowed in java. But as mentioned in previous answer, you mean "templates" for "true generics".

How to access and read JVMs class file members?

I'm not very familiar with JVM and I have an assignment involving the Class file.
Write a java program that when run as
java DissectClassFile file1.class file2.class ...
it will print a summary of each class file as follows:
the name of the class defined by the class file,
its super class and interfaces it implements,
the number of items in the constant pool,
the number of interfaces implemented by the class, and their names,
the number of fields of the class whose name contain the underscore character,
the number of methods of the class whose names contain at least one capital letter
Right off the bat I don't know where to begin. If someone could help me out and point me in the correct direction, I should get the hang of it.
You need to read the Java Virtual Machine Specification. It contains an explanation of the class file format.
There is a class java.lang.Class to access that information. For every Class, you can call MyClass.class (for example, String.class) to get the object with the information for that class.
Most of this information can easily be gleaned loading each class using Class.forName(...) and using the reflection APIs to fish out the information. However the constant pool size is the killer. AFAIK, this can only be determined from the class file itself.
So, your options would seem to be:
Write a bunch of code to read and decode class files. The JVM spec has the details of the class file format.
Use an existing library such as BCEL to take care of the low-level class file parsing.
Use a hybrid of class file parsing (using either of the above) to extract the constant pool size, and the reflection APIs for the rest.
I imagine that your assignment hints at which way they expect you to go. But if not, I'd look at the BCEL approach first.

Using a function in two unrelated Java classes

I have two classes in my Java project that are not 'related' to each other (one inherits from Thread, and one is a custom object. However, they both need to use the same function, which takes two String arguments and does soem file writing stuff. Where do I best put this function? Code duplication is ugly, but I also wouldn't want to create a whole new class just for this one function.
I have the feeling I am missing a very obvious way to do this here, but I can't think of an easy way.
[a function], which takes two String arguments and does soem file writing stuff
As others have suggested, you can place that function in a separate class, which both your existing classes could then access. Others have suggested calling the class Utility or something similar. I recommend not naming the class in that manner. My objections are twofold.
One would expect that all the code in your program was useful. That is, it had utility, so such a name conveys no information about the class.
It might be argued that Utility is a suitable name because the class is utilized by others. But in that case the name describes how the class is used, not what it does. Classes should be named by what they do, rather than how they are used, because how they are used can change without what they do changing. Consider that Java has a string class, which can be used to hold a name, a description or a text fragment. The class does things with a "string of characters"; it might or might not be used for a name, so string was a good name for it, but name was not.
So I'd suggest a different name for that class. Something that describes the kind of manipulation it does to the file, or describes the format of the file.
Create a Utility class and put all common utility methods in it.
Sounds like an ideal candidate for a FileUtils class that only has static functions. Take a look at SwingUtilities to see what I'm talking about.
You could make the function static in just one of the classes and then reference the static method in the other, assuming there aren't variables being used that require the object to have been instantiated already.
Alternatively, create another class to store all your static methods like that.
To answer the first part of your question - To the best of my knowledge it is impossible to have a function standalone in java; ergo - the function must go into a class.
The second part is more fun - A utility class is a good idea. A better idea may be to expand on what KitsuneYMG wrote; Let your class take responsibility for it's own reading/writing. Then delegate the read/write operation to the utility class. This allows your read/write to be manipulated independently of the rest of the file operations.
Just my 2c (+:

Categories

Resources