What's the point of using .class objects? - java

In the past few weeks, I've run into several different peoples' code using .class objects. For example, ArrayList of classes : ArrayList<Class> but how to force those classes to extend some super class?.
I looked them up: http://docs.oracle.com/javase/tutorial/reflect/class/index.html
I'm just wondering why you'd want to use .class objects. I can see getDeclaredFields() and getDeclaredMethods() being potentially useful, but I can't really think of concrete examples as to why I'd actually want to use the .class objects in lieu of something else. Could anyone shed some light on this topic?
Thanks in advance.

I think you misunderstood the concept. Class class has nothing to do with compiled classes (.class).
Class is a class that represents a Java class internal structure, such as fields, methods, etc... This is a compile-time entity, which you can use in your code (even before compiling).
.class is a compiled Java class file, which is Java bytecode. This is not a "code" entity (you cannot use it as a class or object in your code -besides as any file-) and it is not available before compilation.
Reflection (Class is part of the reflection package) is useful when you want to do advanced stuff with the code, like manipulating it, accessing its members, getting information from it, etc...
A typical example where you want to use reflection is making a Java debugger. Since any code can be run on the debugger, you need reflection to get information about the object instances and their structure and show this to the user.

Reflection is one reason to use it. Another good example is dynamically constructing objects at runtime.
For example, the Spring framework uses configuration files that contain the names of Java classes. Somewhere in that code, Spring needs to build object instances of those classes. In this way, the objects are created without the compiler needing to know anything about the Java classes at compile time.

This can be useful when developing an interpreter of a scripting language running on JVM, which has an ability to call Java methods.
Also, might be useful in a system allowing for plugin extensions.

Another use case:
InputStream is = MyClass.class.getResourceAsStream("/some/resource/in/the/jar");

Plug-in are a big use for this.
Dynamically load .class files which are in say, your plugins folder and execute some specified function from said files. Then, you can have 0 or more plug-ins and any combination of them installed for your application at a time.

Related

Manually add a method call to a class file?

I need to manually add a method call to a class file without decompiling and recompiling the code because It depends on thousands of other classes and I don't wan't have to do more than is nessescary. I know java but not how class files are made.
Any help is appreciated.
EDIT:
I am not the owner of the source and I need this to work on any computer, which means I cannot redistribute the sources and have them compiled realtime while my patcher is working.
You have the source code, and you have all other classes compiled. So you can recompile just that source file, passing compiled classes as parameters to java compiler with -classpath option.
You should use ASM or Javaassist to manipulate the bytecode. ASM is a little bit more complex and requires you to understand more about the JVM, but it's faster. Javaassist doesn't require you to know much about the JVM's internals.
However, I don't see why you can't just recompile that single sourcefile? If you only need to add this method once, it's very inefficient to learn ASM or Javaassist.
How about subclassing? Then you don't need to touch the sources.
So if you have the source code and want to add some methods into only one class. Then you don't have to worry about other classes even they are dependent on your current modified class. Re-compiling a file doesn't affect other classes. Since the output will be produced at run-time.
If your class is not declared final and the method you are interested is not final, you can extend the class and override just that method.
Just change the source code, recompile ! Everything will work fine. Subclassing won't work .Because Already existing classes won't know about the new subclass until you change their code to use the new subclass instead of old superclass.
For manual editing of classfiles, I'd recommend Krakatau. (Disclosure, I wrote it). It lets you disassemble a classfile, edit it, and reassemble. There are other assemblers out there, but AFAIK, Krakatau is the only one that supports all the weird edge cases in the classfile format.
The main caveat is that Krakatau by default does not preserve certain optional debugging attributes (specifically LineNumberTable, LocalVariableTable, and LocalVariableTypeTable), since there is no simple way to represent them in a human editable format, and failing to edit them when the bytecode changes will result in a verification error. Most likely you don't actually need this though so it shouldn't matter.
The other caveat of course is that you have to understand bytecode. But if you don't, you won't be able to manually edit classfiles anyway.
I got it now! I Created fake source files with the same names/methods but didn't add anything else except for class and method names. That way I only needed to pack the ones that are directly linked to my Class file. But now compiling takes a few milliseconds whereas it used to take around 124s, Lol. Works great!

How to write Qt plugin system with bindings in other languages?

I am writing an application in Qt that I want to extend with plugins.
My application also has a library that the plugins will use. So, I need a 2 way communication. Basically, the plugins can call the library, and my application which loads the plugins will call them.
Right now, I have my library written in C++, so it has some classes. The plugins can include the header files, link to it and use it. I also have a header file with my interface, which is abstract base class that the plugins must have implemented. They should also export a function that will return a pointer to that class, and uses C linkage.
Up to this point I believe that everything is clear, a standard plugin interface. However, there are 3 main problems, or subtasks:
How to use the library from other languages?
I tried this with Python only. I used SIP to generate a Python component that I successfully imported in a test.py file, and called functions from a class in the library. I haven't tried with any other language.
How to generate the appropriate declaration, or stub, for my abstract class in other languages? Since the plugins must implement this class, I should be able to somehow generate an equivalent to a header in the other languages, like .py files for Python, .class files for Java, etc.
I didn't try this yet, but I suppose there are generators for other languages.
How am I going to make instances of the objects in the plugins? If I got to this point the class would be implemented in the plugins. Now I will need to call the function that returns the instance of the implemented abstract class, and get a pointer to it.
Based on my research, in order to make this work I will have to get a handle to the Python interpreter, JVM, etc., and then communicate with the plugin from there.
It doesn't look too complex, but when I started my research even for the simplest case it took a good amount of work. And I successfully got only to the 1st point, and only in Python. That made me wonder if I am taking the right approach? What are your thoughts on this.. maybe I should not have used Qt in my library and the abstract base class, but only pure C++. It could probably make the things a bit easier. Or maybe I should have used only C in my library, and make the plugins return a C struct instead of a class. That I believe would make the things much easier, since calling the library would be a trivial thing. And I believe the implementation of a C struct would be much easier that implementing C++ class, and even easier that implementing a C++ class that uses Qt objects.
Please point me to the right direction, and share your expertise on this. Also, if you know of any book on the subject, I'd be more than happy to purchase it. Or some links that deal with this would do.
C++ mangles its symbols, and has special magic to define classes, which is sort of hacked on top of standard (C) object files. You don't want your files from other languages to understand that magic. So I would certainly follow your own suggestion, to do everything in pure C.
However, that doesn't mean you can't use C++. Only the interface has to be C, not the implementation. Or more strictly speaking, the object file that is produced must not use special features that other languages don't use.
While it is possible for a plugin to link to your program and thus use functions from it, I personally find it more readable (and thus maintainable) to call a plugin function after loading it, passing an array of function pointers which can be used by the plugin.
Every language has support for opening shared object (SO or DLL) files. Use that.
Your interface will consist of functions which have several arguments and return types, which probably have special needs in how they are passed in or retrieved. There probably are automated systems for this, but personally I would just write the interface file by hand. The most important is that you properly document the interface, so people can use any language they want, as long as they know how to load object files from their language.
Different languages have very different ways of storing objects. I would recommend to make the creator of the data also the owner of the memory. So if your program has a class with a constructor (which is wrapped in C functions for the plugin interface), the class is the one creating the data, and your program, not the plugin, should own it. This means that the plugin will need to notify your program when it's done with it and at that point your program can destroy it (unless it is still needed, of course). In languages which support it, such as Python and C++, this can be done automatically when their interface object is destroyed. (I'm assuming here that the plugin will create an object for the purpose of communicating with the actual object; this object behaves like the real object, but in the target language instead of C.)
Keep any libraries (such as Qt) out of the interface. You can allow functions like "Put resource #x at this position on the screen", but not "Put this Qt object at this position on the screen". The reason is that when you require the plugin to pass Qt objects around, they will need to understand Qt, which makes it a lot harder to write a plugin.
If plugins are completely trusted, you can allow them to pass (opaque) pointers to those objects, but for the interface that isn't any different from using other number types. Just don't require them to do things with the objects, other than calling functions in your program.

Creating a new Java application using the compiled class files

I have an application that is developed in Java that has nice GUI and all. I don't have the source code and also the dll's of that. But I have the compiled classes of that application (.jar files).
Now, I want to automate that application. I mean the application needs manual intervention.
Can I use that compiled classes so that I can use its functions to automate the functionality of that application?
If so, how would this be done?
You shouldn't have to "got the compiled classes out of that application (.jar)". A better idea would be to treat it just like any other 3rd party JAR and add it to your CLASSPATH when you compile and run.
You'll write your own class that instantiates an instance of that 3rd party class and calls its methods, just like any class you get from the JDK.
You may not be able to alter that class; you might not want to even if you could.
If you must have new functionality, the OO way would suggest that you should extend that class, if you can, and override its method according to your needs.
Put that .jar into your classpath and use what ever you want from that application. If you need to use private fields or methods also you can use Reflection API for that. There is no restrictions of using objects from .jar file.
You should beware of infringing on any copyrights if the application you are referring to is proprietary. Otherwise, any java decompiler will get you the source code from those class files.

Possible to use two java classes with same name and same package?

Is it possible to import and use two different classes with the same name and package in java?
For example, let's say I have two classes named "com.foo.Bar" that are slightly different. I'd like to be able to use both, but I have a restriction (because of stupid reflective crap) that forces me to keep the names and packages the same.
Is there some feature of java that would allow me to import and isolate each of these classes?
To elaborate, I changed my avro schemas in ways that they shouldn't have ever been changed (oops!) and now I'd like to go back and change the old avro files that can't be read with my new schema into files that can be read by my new schema. Avro seems to force you to use a specific class and package name to load the files.
Yes there is. You would need to implement your own Classloader and play some games to be able to access both during runtime.
I'm sure this is possible, because I ran into a very hard to debug issue where someone had a weird Classloader in their product that was messing up loading libraries and providing 2 different versions of the same file from 2 different versions of the library.
However, this sounds like an INCREDIBLY bad idea. I'd go back and find a different way of fixing your issue. This will only bring you heartache in the long run. Heck, it probably already is, as you investigate class loaders.
EDIT: To be specific, you cannot "import" both. But you can access both at runtime.
No, java packages are used precisely to avoid that problem.
Yes it is. It does require you to make your own ClassLoader, though
I had made a demo of that on github to!
If you really most definitely must do something like this, you can achieve it by using different classloaders and possibly reflection.
This is not the way Java works and it's not allowed on purpose - you shouldn't be doing stupid things which will screw up things for you.
There are no namespaces in Java, only in C#, so I assume you mean packages. There can only be one fully qualified name per project.
Technically it can be done using some low-level trickery such as rewriting the byte-level code. As far as I know the different java crypter/encrypters work like that - they have a lot of classes called A.class B.class C.class etc.
It sounds to me like you need to define your method signatures in an interface called com.foo.Bar. Then provide two different concrete implementations of the interface (say, com.foo.DefaultBar, and com.foo.SpecialBar). This way, you can program against the interface type, and switch between the two different implementations as required.
Can you elaborate on what you mean by "reflective crap"? That may provide insight into your exact issue.
Don't mess with the class loader or any other low level trickery. The best way to solve such issues it to have a clear design in the first place that anyone can understand.
As already mentioned writing your own Classloader or additionally use a OSGi framework like Equinox which does the classloading for you

Class Loading to an interface

I'm quite restricted in the platform I'm currently working on (JDK 1.3, BD-J). One JAR file I would like to use attempts to perform a self-integrity check on load and if it fails it goes into an inoperable state. It's quite difficult to find out why this is happening but most sources point to that it cannot find/access it self through the BD-J structure, so it dies.
This rules out using it at load time and instead to load it in the application itself. This is quite a large library so I have to create quite an amount of interfaces so I can cast a loaded object to it and potentially use it. This is where my problem lies.
The interfaces are loaded on normal load time and the library is then loaded during run time and casted to the previously loaded interfaces, is this a problem? I'm receiving ClassCastException
I've based the interfaces off the libraries public methods as best I can, but when I attempt to cast to an interface I receive the ClassCastException. Note: It all loads fine, I can access constructors and read the method names. Just when casting it for it to be useable it fails.
The interface packages are different in my project to that of the toolkit, does this matter?
I'm running out of ideas, is there something I have overlooked?
Thanks.
I'm not sure I fully grok what your problem is - maybe some more details about what the class hierarchy looks like would help in figuring out the situation. From what you wrote I can guess two possible scenarios:
.1. The classes you want to use do not implement any interface.
In this case no matter what you name your interfaces, it will not work, since the classes you're loading do not implement them. You're stuck with using reflection if you can't load that jar as part of the boot classpath.
.2. The classes you want implement some interface that you're trying to replicate.
In this case you interface implementation must match the exact qualified name of the interface the classes are implementing. Normally, when loading the classes from the jar, the class loader will pick up the interfaces from the system class loader first, thus loading your interfaces, and everything should work.
If they use some crazy internal class loader, though, they might still try to load their own interfaces. You could try to figure out if that's the case by using "-XX:+TraceClassLoading", although I don't know if the 1.3 jre will understand that option.
Now if you're willing to experiment more, you could also try another approach. Write your own class loader that loads both the classes from that jar and the code you want to run. That way, your code would be able to directly refer to the classes in that jar, but to start your application the "main" method will have to be one that initializes this classloader, loads the "real" main class using reflection, and executes its main() method also via reflection.
Most probably the classes are loaded by different class loaders. http://mindprod.com/jgloss/classloader.html may give some idea.

Categories