Can a Java program access its own source code? - java

In Java, I'd like to find a way to allow a program to access its own source code, mainly for debugging and metaprogramming purposes (such as printing a method signature at runtime, or allowing a program to read its own comments, or allowing a Java class to print all methods of a certain type, or allowing a program to generate a new version of its own source code, etc).
Is there any way to allow a Java program to access a copy of its own source code, and read it line-by-line?
//this is the first line of the program
//this method is not implemented
public class inspectSourceCode(){
public static String getLine(int lineNumber){
//get the line of the program's own source code as a string,
//this is not currently implemented
}
//this method is implemented
public static void main(String[] args){
System.out.println(getLine(0));
//should print "//this is the first line of the program",
//if the method getLine works correctly
}
}

You could just directly access the .java file in the code. Just point it to the correct directory and access the file as you would any other.
The program is not running the java file itself, there are compiled files instead that are used at runtime.

I'm trying to set properties of each method
I'd suggest you to use annotations and then get them with Method.getAnnotation

Did you checked ASM? http://asm.ow2.org/
But I think, what you are trying to do is very cpu-expensive.

You COULD theoretically use a decompiler library in your source code to potentially get access to the classes, but keep in mind due to optimization and/or obfuscation etc you might not be able to reliably do a 1-1 translation between bytecode and Java code. Also keep in mind that you don't even necessarily have the line #s available to you if the code was not compiled with debugging information built in.

Can a Java program access its own source code?
In general no. The source code is typically not available on the execution platform.
In the sub-cases where the source code is available, then yes (of course) a program can read it using the standard Java I/O APIs. However, there are no standard APIs that are specific to the task of reading source code.
... mainly for debugging purposes (such as printing a method signature at runtime, or allowing a program to read its own comments, or allowing a Java class to print all methods of a certain type)
There is no technical reason why you could not do those things, but it strikes me that you would have a lot of work to do before such a tool got to the point of being useful. And, frankly, a typical Java IDE's source code debugger does pretty much all of these things already, so I don't really see the point of that effort.

Related

How can i use redefineClasses() method in javaagents

I have been using premain() with addTransformer(). Since, it gives javassist.ClassNotFound exceptions for certain classes when i run the agent with a server, i thought to try the agentMain() with redefineClasses(). I went through many links, but so far i am unable to find a piece of code that gives me clear idea on how to set up a simple java agent using these two methods. Some help would be really appreciated.
Can we use redefineClasses() with premain()? (When we use redefineClasses() do we still need the transform method?)
I am trying to instrument set of methods of set of classes, where i know the fully qualified name of those classes as com.test.Foo. I wanted to instrument them without going through the entire set of classes loaded onto JVM. I have been reading those documents back and forth, but still i am unable to get a clear idea on how to use that redefineClasses method?
You can call redefineClasses from anywhere, also from a premain method which is nothing but an extension to a normal Java program run by the same JVM process previous to a main method.
A trivial example for running a redefinition is:
instrumentation.redefineClasses(new ClassDefinition(Foo.class, new byte[] {...}));
This way, Foo is set to be represented by the byte array that must contain a valid class file for Foo where all signatures of fields and methods are the same as by the loaded Foo.class. You can use a tool like ASM for instrumenting the class.
If you really only want to instrument Foo, then this might just be the way to go instead of using a ClassFileTransformer.

Dynamically build java/scala method body at runtime and execute it

Suppose I have the following Interface in java:
public interface DynamicMethod {
String doit();
}
I would like to build an Object during runtime which conforms to the above interface such that I inject doit method body in it and then execute it? Is this possible with Java Reflection API, or any other way? Or probably in some way in Scala?
Note that doit body for my objects would be dynamic and are not known a priori. You can assume that in run-time an array CodeArray[1..10] of Strings is provided and each entry of this array holds the code for each doit method. I would appreciate if you could answer with a sample code.
The context:
I try to explain the context of the problem; nonetheless, the above question still remains independent from the context.
I have some commands say C1,C2, ...; each command has certain parameters. Based on a command and its parameters the system needs to perform a certain task (which is expressible using a java code.) I need that these commands are stored for future execution based on user demand (so the CodeArray[1..10] in the above holds this list of java codes). For example, a user chooses a command from the list (i.e., from the array) and demands its execution.
My thought is that I build an engine that based on the user selection, loads the corresponding command code from the array and executes it.
With your context that you added, it sounds to me like you have an Interpreter..
For example, SQL takes input like "SELECT * FROM users", parses and builds a tree of tokens that it then interprets.
Another example: Java's regex is an interpreter. A string like "[abc]+" is compiled into tokens, and then interpreted when executed. You can see the tokens (called Nodes) it uses in the source code.
I'll try to post a simple example later, but the Interpreter Pattern doesn't use dynamically generated code. All of the tokens are concrete classes. You do have to define all possible (valid) user input so that you can make a token to execute it however. SQL and regex has a defined syntax, you will need one also.
I think Byte Buddy would be helpful in your case. It's an open source project maintained by a very well respected Java developer.
Take a look at the Learn section, they have a very detailed example there:
http://bytebuddy.net/#/tutorial
Currently it's not very clear what's your aim. There are many approaches to do this depending on your requirements.
In some cases it would be enough to create a Proxy and an InvocationHandler. Sometimes it's reasonable to generate Java source, then invoke JavaCompiler in runtime and load the generated class using URLClassLoader (probably that's your case if you're speaking about strings of code). Sometimes it's better to directly create a bytecode using libraries like ASM, cglib or BCEL.

why do we use java files without main ? What purposes does it meet ? How useful it is .?

I am new to java programming and i just came across to a java program composed of many files and only one of the file had a main function while others did not. I didn't really understood that why don't we have a main function in every java file.
Not every file needs a "main" function. For example, you may want to import a file with specific function or class. In this case (a java file without a "main" function), the java file simply represents a chunk of code, which is added to your program. So it doesn't need a separate "main" function, if you already have one.
In java, main() is an entry point to a program/application. Sometimes in a application we just need only one entry point to start the program and from this point other necessary code are used.
But not all application necessarily need an main() method - like web application or java applet where a container initiate the application/program.
Every Java program must have an entry point, and that entry point must have a certain signature. Which, as you have noticed, is public static void main(String[] args)
After that, the class that is the entry point can create instances of other classes and/or invoke their methods, or invoke static class-level methods. It is not necessary for those classes to have an entry point, because the program is already running (executing your code) in the Java Virtual Machine (JVM).
You'll notice that a common error novice (and sometimes even seasoned) programmers make is trying to run a program for which the runtime environment cannot find an entry point. E.g., Eclipse: Java, no main method found (in this example, the problem was that the OP had the wrong method signature). The runtime has to find something to, well, RUN.
If your code is going to be run by some other code (e.g., you are developing a library or an API that contains functionality that will be used as part of another application) it may not be necessary for you to have a main method. If you look through the .jar files of some of the standard libraries using your IDE, you should discover that very few of them have classes with a main method - this is because they are not intended to be run alone, but rather in the context of another application.
The public void main(String args[]) method in java is the entry point to the program. If it is run directly, it will start from the main method. However, not every class that you might make in Java is an acceptable entry point. In fact, in many applications, you should have exactly one main method. There is generally not too much need for more. Some java libraries has no main method anywhere at all. This code is generally designed so that it can be used by other java code, and often has no sensible way to run itself. It's not designed to do that. It is designed to help other programs that do.
What classes without a main method are used for, is a) to provide functionality for other java programs (dependancies for instance), b) to provide additional functionality to the program that is invoked through the main method.
Here is a couple example files that illustrate the second.
MainExample.java
public class MainExample{
public static void main(String args[]){
OtherClass other = new OtherClass()
other.doExpensiveComputation1();
other.doExpensiveComputation2();
}
}
OtherClass.java
public class OtherClass{
public void doExpensiveComputation1(){
//do stuff here
}
public void doExpensiveComputation2(){
//do other stuff here
}
}
Now, you might be asking, "couldn't I just write those methods inside the main class?". In some cases the answer might be yes, but for more complex code, it generally isn't. In some cases it will be impractical simply because it clutters up the main class too much to keep track of. It is much easier to keep track of code that keeps its classes in different files.
Execution of Java program always starts from Main method.Class having main method is the entry point for the program and further from there you can get the rest of the desired functionality.
If You want you can have main method in each java file, which will behave as multiple entry points for your program.

Java to JavaScript using GWT compiler

I have some Java code written that I'd like to convert to JavaScript.
I wonder if it is possible to use the GWT compiler to compile the mentioned Java code into JavaScript code preserving all the names of the methods, variables and parameters.
I tried to compile it with code optimizations turned off using -draftCompile but the method names are mangled.
If GWT compiler can't do this, can some other tool?
Update
The Java code would have dependencies only to GWT emulated classes so the GWT compiler would definitely be able to process it.
Update 2
This Java method :
public String method()
got translated to this JavaScript funciton :
function com_client_T_$method__Lcom_client_T_2Ljava_lang_String_2()
using the compiler options :
-style DETAILED
-optimize 0
-draftCompile
So names can't be preserved. But is there a way to control how they are changed?
Clarification
Say, for example, you have a sort algorithm written in Java (or some other simple Maths utility). The method sort() takes an array of integers. and returns these integers in an array sorted. Say now, I have both Java and JavaScript applications. I want to write this method once, in Java, run it through the GWT compiler and either keep the method name the same, or have it change in a predictable way, so I can detect it and know how to change it back to sort(). I can then put that code in my JavaScript application and use it. I can also automatically re-generate it if the Java version changes. I have a very good reason technically for this, I understand the concepts of GWT at a high level, I'm just looking for an answer to this point only.
Conclusion
The answer to the main question is NO.
While method name can be somewhat preserved, its body is not usable. Method calls inside it are scattered throughout the generated file and as such, they can't be used in a JavaScript library which was the whole point of this topic.
Although you can set the compiler to output 'pretty' code, I suggest you write export functions for the classes you want to call from outside your GWT project. I believe somewhere in the GWT documentation it's detailed how to do this, but I couldn't find it so here an example I just created.
class YourClass {
public YourClass() {
...
}
public void yourMethod() {
...
}
public static YourClass create() {
return new YourClass();
}
public final static native void export() /*-{
$wnd.YourClass = function() {
this.instance = new #your.package.name.YourClass::create()()
}
var _ = $wnd.YourClass.prototype;
_.yourMethod = function() {this.instance.#your.package.name.YourClass::yourMethod()()}
}-*/;
}
EDIT
To elaborate, your code will get obfuscated like normal, but thanks to the export function, you can easily reference those functions externally. You don't have to rewrite anything from your Java class in JavaScript. You only write the references in JavaScript, so you can do this:
var myInstance = new YourClass();
myInstance.yourMethod();
Of course you have to call the static export method from somewhere in your GWT app (most likely in your EntryPoint) to make this work.
More info about referencing Java methods from JavaScript:
http://code.google.com/webtoolkit/doc/latest/DevGuideCodingBasicsJSNI.html#methods-fields
No - this isn't possible with the GWT compiler, since the GWT compiler is build to generate optimized and very performant JavaScript out of Java.
The big advantage is, that you can maintain your projekt in Java and compile it with GWT to JavaScript. So there is no need to prevent the variable-names and method-names in the JavaScript result, since all changes and work is done in the JAVA-sources.
Working in the JavaScript-output of GWT just isn't that easy and is really a lot of work!
Update:
By a hint of David, I found the Compiler-Option "-style". You can have a try with the following options:
-style=PRETTY -optimize=0
I have no idea if this will really generate "human readable" code. I think it won't, since the GWT framework will still be part of the resulting JavaScript and so it will be difficult to make changes to the JavaScript-result. Have a try and let us know ...
Maybe I can answer your second question: "If GWT compiler can't do this, can some other tool?"
I am using Java2Script for quite a while now, also on quite large projects. Integration with native JavaScript is fine, names are preserved, and after some time one can even match the generated JavaScript (in the browser debugger) with the original Java code with little effort.
Udo
You can "export" your function by writing inline JavaScript that calls it, and there is a tool gwt-exporter that does this automatically when you annotate classes and methods with #Export and similar. More information: https://code.google.com/p/gwtchismes/wiki/Tutorial_ExportingGwtLibrariesToJavascript_en

GetPropertyAction vs System.getProperty in obtaining system variables

I have been using quite a lot of
System.getProperty("property")
in order to obtain environmental information. However, it seems to me that Sun prefers the following :
(String) java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("property"));
The strange thing is that this code involves a cast and as a result should be slightly slower than the
System.getProperty
implementation, that only uses a security manager and then instantly fetches the property from the instance variable props. My question is why did Sun chose to use the second method to obtain most environmental variables in their code internally, while
System.getProperty
seems like the faster way to go?
Both methods have a different meaning, and thus the right one has to be used depending on what the current code needs to do.
The code System.getProperty("property") says "Give me the value of the property, if the current security context allows me to read it."
The code that uses doPrivileged says "Give me the value of the property, if the current class (where this line of code is in) is allowed to read it."
The difference comes into play, when the protection domain of the current class is different from the currently active security context.
For example, consider a framework which executes the code of a plugin, which is untrusted. So the framework uses a SecurityManager to restrict the actions of the untrusted plugin code. But of course the plugin may call some methods of the framework, and suppose that one of these methods needs to read a property. Now as the method is called from untrusted restricted code, it is itself restricted and thus reading the property would fail. But of course the framework trusts itself and wants itself to be able to read that property, even in the case that somewhere in the call stack is untrusted code. That's when you need to use doPrivileged. It basically says "no matter what is up there in the call stack, I am a piece of framework code, and I am allowed to do whatever the framework code is allowed to do". So reading the property using the second method succeeds.
Of course one needs to be careful when using doPrivileged in order to not let the (untrusted) calling code do to much. If, for example, the framework code offers the following method to the plugin:
public String getProp(String key) {
return (String) java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction(key));
}
this would completely invalidate the policy that the untrusted code is not allowed to read system properties, because it can just use your method.
So use this method only when you know it is safe to do it, and only when you need it (which is, when you want your code to be able to do more than some other code should be able to do directly). Inside a normal application (which usually runs with no SecurityManager or the same security context for all code), there is no difference and the first method should be used.
I would recommend to stick with System.getProperty() since sun.security.action.GetPropertyAction seems to be proprietary to SUN and will not work on all Java VM implementations. Even the compiler warns you about it as:
warning: sun.security.action.GetPropertyAction is Sun proprietary API and may be removed in a future release
To understand what it actually means see this answer.
The reason to use a class like sun.security.action.GetPropertyAction is to avoid loading several, basically identical classes.
If you wrote:
(String) java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<java.lang.String>() {
String run() {
System.getProperty("property");
}
}
);
Each time you wanted to get a system property, you would load a new class for each getProperty call. Each class takes system resources and lives as long as the containing ClassLoader (forever for the bootclassloader).
Check out the javap output for more details:
javap -c -v -p sun.security.action.GetPropertyAction

Categories

Resources