Given a Java application which was written with performance in mind (i.e. methods are deliberately not declared 'strictfp' in the source code), is it possible to allow users to run the entire application in strictfp mode?
It looks like a crude approach would be to simply add the "strictfp" attribute to all methods of all classes using a custom class loader written using javassist. This would be similar to:
http://www.verious.com/qa/no-strictfp-in-scala-workarounds/
However, the class loader would need to add the strictpf attribute to all class methods in the application, including private ones. (The application is simply too large and complex to explicitly list all possible methods which might requre the strictfp attribute.)
The reflection API in javassist does not seem to support listing private methods:
http://www.csg.ci.i.u-tokyo.ac.jp/~chiba/javassist/html/javassist/CtClass.html#getMethods()
Is what I want to do possible in javassist (or at all via the custom class loader approach)?
I don't know if this will help you, but if you could change to using the Oracle JRockit JVM, it has a JVM option to enable strictfp globally - '-XX+:-StrictFP`
(There is a '-XX+:-UseStrictFP' option on Hotspot JVMs, but it has the reverse effect to what you want.)
Reference:
http://docs.oracle.com/cd/E15289_01/doc.40/e15062/optionxx.htm#BABHBDAH
http://stas-blogspot.blogspot.com.au/2011/07/most-complete-list-of-xx-options-for.html
Related
I would like my projekt to switch at startup between backend libraries, with option to not shade both of them into resulting Jar, while having full compile-them visibility of both.
I would also like to avoid loading backends using Class.forName.
Can you help me understand if any of these will lead to a ClassNotFoundError for unshaded library and which will not?
Leaving an unused class field, of type from this library
Leaving an unused method, with arguments or return from this library
Referencing this library in a backend class that will only be loaded conditionally like backend = isNewBackend ? new FancyBackend() : new OldBackend()
If all of these result in error, is there an easier strategy for this?
In Java, what's the proper way of using an optional dependency without ClassNotFoundError?
The simple way is to use Class.forName.
I would also like to avoid loading backends using Class.forName.
Erm ... OK.
Can you help me understand if any of these will lead to a ClassNotFoundError for unshaded library and which will not?
If I understand what you are proposing correctly, none of them will work.
Leaving an unused class field, of type from this library
Loading the class that defines that field will trigger1 loading the library that defines the type of the field.
Leaving an unused method, with arguments or return from this library
Loading the class that defines that method will trigger1 loading the library that defines the argument or return type.
Referencing this library in a backend class that will only be loaded conditionally like:
backend = isNewBackend ? new FancyBackend() : new OldBackend()
The code that does that calculation needs to be defined in a class. To running that code that is liable to trigger1 loading both the FancyBackend and OldBackend classes to verify the code.
If you wanted to avoid explicit Class.forName calls, you could potentially implement your optional dependency as a custom Service Provider Interface (SPI). That gives you additional flexibility, but it is more complicated than simply using Class.forName.
Here are some references for SPIs:
The javadocs for java.utils.ServiceLoader.
Creating Extensible Applications from the Oracle Java™ Tutorials. (This tutorial is outdated.)
Java Service Provider Interface from Baeldung.
1 - Per Does the JVM throw if an unused class is absent? if the JVM implements lazy class loading, loading may not be triggered by mentioning a class in a method or field signature. However, lazy loading is implementation dependent and (AFAIK) not specified. So relying on the JVM to do it will make your application platform dependent.
For some of our flows, we'll have some output attributes (a checksum for instance) that we can't generate directly through DataWeave so we chose to calculate them using Java functions and we have too possibilities :
Use a Java component and put the result on a variable using a transformer class
Define a global function that calls a static method from a class and use it in a Transform Message component
I know that we can have some performance problems with static method as they can't be garbage collected. What are the pros and cons of these 2 choices ?
I think it depends on the complexity of the function. Anything you can do in Java you can do directly using MVEL in a global function - no need to call out to a Java static method.
The main benefit of using a global function is that you can use MEL/MVEL that may make the function a lot less verbose because of handy MVEL features like property navigation, folds/projections etc. and allows you to access Mule vars/props/payload easily using MEL like #[flowVars.].
But I think if it's a very complicated function then a Java component may be easier for readability/maintenance etc. Also a Java component may be easier to modularise and share with other projects separately.
There may be performance benefits with one over the other, but potentially negligible or you could profile it to see the performance comparison.
From wikipedia:
reflection is the ability of a computer program to examine and modify the structure and behavior (specifically the values, meta-data, properties and functions) of an object at runtime.
Can anyone give me a concrete example of modifying the structure of an object? I'm aware of the following example.
Object foo = Class.forName("complete.classpath.and.Foo").newInstance();
Method m = foo.getClass().getDeclaredMethod("hello", new Class<?>[0]);
m.invoke(foo);
Other ways to get the class and examine structures. But the questions is how modify is done?
Just an additional hint since the previous answers and comments answer the question concerning reflection.
To really change the structur of a class and therefore its behaviour during runtime look at Byte code instrumentaion and in this case javassist and asm libs. In any case this is not trivial task.
Additionally you might have a look at aspect programming technic, which enables you to enhance methods with some functionallity. Often used to introduce logging without the need to have a dependency of the logging classes within your class and also dont have the invocations of the logging methods between the problem related code.
In English reflection means "mirror image".
So I'd disagree with the Wikipedia definition. For me, reflection is about runtime inspection of code, not manipulation.
In java, you can modify the bytecode at runtime using byte code manipulation. One well known library and in wide spread use is CGLIB.
In java, reflection is not fully supported as defined by the wikipedia.
Only Field.setAccessible(true) or Method.setAccessible(true) really modifies a class, and still it only changes security, not behaviour.
Frameworks like e.g. hibernate use this to add behaviour to a class by e.g. generating a subclass in bytecode that accesses private fields in the parent class.
Java is still a static typed language, unlike javascript where you can change any behaviour at runtime.
The only method in reflection (java.lang.reflect) to modify object's class behaviour is to change the accessibility flag of Constructor, Method and Field - setAccessible, whatever wiki says. Though there are libraries like http://ru.wikipedia.org/wiki/Byte_Code_Engineering_Library for decomposing, modifying, and recomposing binary Java classes
I'm working on my first real project with Java. I'm beginning to get comfortable with the language, although I have more experience with dynamic languages.
I have a class that behave similar to the following:
class Single
{
public void doActionA() {}
public void doActionB() {}
public void doActionC() {}
}
And then I have a SingleList class that acts as a collection of these classes (specifically, it's for a 2D Sprite library, and the "actions" are all sorts of transformations: rotate, shear, scale, etc). I want to be able to do the following:
class SingleList
{
public void doActionA() {
for (Single s : _innerList) {
s.doActionA();
}
}
... etc ...
}
Is there any way to simply defer a method (or a known list of methods) to each member of the inner list? Any way without having to specifically list each method, then loop through each inner member and apply it manually?
To make things a bit harder, the methods are of varying arity, but are all of return type "void".
Unfortunately Java does not readily support class creation at runtime, which is what you need: the SingleList needs to be automatically updated with the necessary stub methods to match the Single class.
I can think of the following approaches to this issue:
Use Java reflection:
Pros:
It's readily available in the Java language and you can easily find documentation and examples.
Cons:
The SingleList class would not be compatible with the Single class interface any more.
The Java compiler and any IDEs are typically unable to help with methods called via reflection - errors that would be caught by the compiler are typically transformed into runtime exceptions.
Depending of your use case, you might also see a noticeable performance degradation.
Use a build system along with some sort of source code generator to automatically create the SingleList.java file.
Pros:
Once you set it up you will not have to deal with it any more.
Cons:
Setting this up has a degree of difficulty.
You would have to separately ensure that the SingleList class loaded in any JVM - or your IDE, for that matter - actually matches the loaded Single class.
Tackle this issue manually - creating an interface (e.g. SingleInterface) or a base abstract class for use by both classes should help, since any decent IDE will point out unimplemented methods. Proper class architecture would minimize the duplicated code and your IDE might be able to help with generating the boilerplate parts.
Pros:
There is no setup curve to get over.
Your IDE will always see the right set of classes.
The class architecture is usually improved afterwards.
Cons:
Everything is manual.
Use a bytecode generation library such as Javassist or BCEL to dynamically generate/modify the SingleList class on-the-fly.
Pros:
This method is extremely powerful and can save a lot of time in the long term.
Cons:
Using bytecode generation libraries is typically not trivial and not for the faint-hearted.
Depending on how you write your code, you may also have issues with your IDE and its handling of the dynamic classes.
I wonder if there's an easy way to determine which classes from a library are "used" by a compiled .NET or Java application, and I need to write a simple utility to do that (so using any of the available decompilers won't do the job).
I don't need to analyze different inputs to figure out if a class is actually created for this or that input set - I'm only concerned whether or not the class is referenced in the application. Most likely the application would subclass from the class I look for and use the subclass.
I've looked through a bunch of .Net .exe's and Java .classes with a hex editor and it appears that the referenced classes are spelled out in plaintext, but I am not sure if it will always be the case - my knowledge of MSIL/Java bytecode is not enough for that. I assume that even though the application itself can be obfuscated, it'll still have to call the library classes by the original name?
Extending what overslacked said.
EDIT: For some reason I thought you asked about methods, not types.
Types
Like finding methods, this doesn't cover access through the Reflection API.
You have to locate the following in a Reflector plugin to identify referenced types and perform a transitive closure:
Method parameters
Method return types
Custom attributes
Base types and interface implementations
Local variable declarations
Evaluated sub-expression types
Field, property, and event types
If you parse the IL yourself, all you have to do is process from the main assembly is the TypeRef and TypeSpec metadata, which is pretty easy (of course I'm speaking from parsing the entire byte code here). However, the transitive closure would still require you process the full byte code of each referenced method in the referenced assembly (to get the subexpression types).
Methods
If you can write a plugin for Reflector to handle the task, it will definitely be the easiest way. Parsing the IL is non-trivial, though I've done it now so I would just use that code if I had to (just saying it's not impossible). :D
Keep in mind that you may have method dependencies you don't see on the first pass that neither method mentioned will catch. These are due to indirect dispatch via the callvirt (virtual and interface method calls) and calli (generally delegates) instructions. For each type T created with newobj and for each method M within the type, you'll have to check all callvirt, ldftn, and ldvirtftn instructions to see if the base definition for the target (if the target is a virtual method) is the same as the base method definition for M in T or M is in the type's interface map if the target is an interface method. This is not perfect, but it is about the best you can do for static analysis without a theorem prover. It is a superset of the actual methods that will be called outside of the Reflection API, and a subset of the full set of methods in the assembly(ies).
For .NET: it looks like there's an article on MSDN that should help you get started. For what it's worth, for .NET the magic Google words are ".net assembly references".
In Java, the best mechanism to find class dependencies (in a programmatic fashion) is through bytecode inspection. This can be done with libraries like BCEL or (preferably) ASM. If you wish to parse the class files with your own code, the class file structure is well documented in the Java VM specification.
Note that class inspection won't cover runtime dependencies (like classes loaded using the service API).