Does Java Instrumentation Agent support New Method Definition in a class? - java

I reloaded on of my test application classes using Instrumentation#redefineClasses(ClassDefinition) method. When I tried adding a new method in the class file and call it from an existing method. It was not happy to for me to do so. But when I called some existing method and other Java Built-In Library methods, it was working fine.
My question is - Is this limitation known/acknowledged by Oracle or Open JDK implementations? I suspect even if you can redefine/retransform your classes using INstrumentation Manifest.MF file - there must be somre sort of limitations to how far you can go with it.
Does anyone have any experience in this thing?

From Instrumentation.html#redefineClasses:
The redefinition may change method bodies, the constant pool and attributes. The redefinition must not add, remove or rename fields or methods, change the signatures of methods, or change inheritance. These restrictions maybe be lifted in future versions. The class file bytes are not checked, verified and installed until after the transformations have been applied, if the resultant bytes are in error this method will throw an exception.
So the answer would be no, it's not possible.

Related

Java - How to avoid static and default methods in interface

My question is rather theoretical:
Lets say I have Java 8 project using static and default methods in interfaces. I need to get rid of them because I am porting the code to Java 7 (lets say it is an Android app prior to Android N).
How to do that? I know there is Retrolambda plugin for that and I successfully use it. But I am thinking about "pure" solution done by altering the code. What are the options?
I know I can remove static and default methods from interface and put them into abstract class that implements this interface and then alter the code wherever there is reference to that interface (this is what Retrolambda does, if I understood the process correctly).
My teacher had indicated it can be done just by "suitable change in interface definition" without using additional class. But so far I failed in finding the solution. I tried putting implementations directly into target classes but that caused a series of troubles in my particular project.
Anyone have some idea or clue I am missing?
I think it is at first questionable that you actually used such a thing in your Java8 project. Interface should remain without implementations. Default methods were introduced mainly for APIs backward compatibility(if method has to be added to Interface from previous versions and you can't afford to force users of API to change their code and you don't like creating InterfaceV2). Not for "daily usage".
I think when porting, you should just export the methods to the static *Util classes. This way you can reuse it and you are not breaking the main principle of Interface.

How to resolve deprecated Tess4j method getInstance()?

I am doing an OCR project. getInstance() in tess4j is deprecated. I can't use Tesseract.Tesseract() even which gives an error. How can I solve this?
Code with Tesseract.getInstance()
Code with Tesseract.Tesseract()
[![Code with Tesseract.Tesseract()][2]][2]
This is what is displayed when I compiled the program after I inserted
Tesseract tess = new Tesseract() ;
enter image description here
Deprecated methods can still be used. The #Deprecated annotation just means that the library developer plans to stop supporting this method (or remove it from the library) in a future release.
More precisely, from the #Deprecated documentation,
A program element annotated #Deprecated is one that programmers are discouraged from using, typically because it is dangerous, or because a better alternative exists.
You may want to check these out:
What does it mean for a method to be deprecated?
The constructor Date(...) is deprecated. What does it mean? (Java)
Is it wrong to use Deprecated methods or classes in Java?
How and When To Deprecate APIs (Oracle official documentation)
What does the deprecated API warning mean?
It is not a good practice, however, to use deprecated methods and classes, as they may lead to future bugs and compilation problems in your system if the methods or classes are removed and you update the library versions.
However, in your case, Tesseract() is a class constructor. You are making the wrong call, as the correct one would be
Tesseract instance = new Tesseract();
Have a look at the Tess4j documentation to learn more about the Tesseract class.
Tesseract() is a constructor, so you need to use new Tesseract() to get one.

Listing the methods called from a java class?

I'm investigating ways to ensure a java class only calls a limited set of allowed methods from other classes. The usecase I have receives the class via the standard java serialization.
The approach I want to try is to simply list the methods it calls and only run the code if it passes a short whire list.
The question I have : how do I list the methods used in that class?
This is not a perfect solution but you coud use this if you can't find something better. You can use javap, if you're in Linux, run in the command line (or run a proccess using Runtime.exec()): javap -verbose /path/to/my/classfile.class | grep invoke and you'll have the binary signatures that the class "calls" from other classes. Yes, I know, it's not what you wanted but you could use it as a last resource.
If you need a more "javaish" solution, you could have a look at a java library called "asm": http://asm.ow2.org/
You could pass a dynamic proxy object to the caller, which inside checks the methods against your white list and throws exception when the call is not allowed.
Dynamic proxies basically allows you to insert piece of code between the caller's method invocation and the actual invocation of the called method.
I'd really think through though to if you really need this. Dynamic proxies are useful but they can also be very confusing and annoying to debug.

Using reflection to modify the structure of an object

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

How to determine which classes are referenced in a compiled .Net or Java application?

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).

Categories