Is there a tool/library that allows me to import the java packages automatically outside the IDE?
For instrance if I type in notepad something like:
JFrame f = new JFrame();
Then run this magic tool, and then have automatically written as:
import javax.swing.JFrame
....
JFrame f = new JFrame();
Is there something like that? This is what comes to my mind as sample usage:
import java.io.File;
public class TesteImport {
public static void main(String[] args) {
AutoImport autoImport = new AutoImport();
File clazz = new File("SampleClazz.java");
autoImport.setImportClass(clazz);
autoImport.addLib("LibA.jar");
autoImport.addLib("LibB.jar");
autoImport.importAll();
}
}
Even if there is such a tool, it won't work always automatically without user input.
If you have for example this code:
List myList;
It has to ask, if the List should be from java.awt.List or java.util.List.
In Eclipse, you have Crtl-Shift-O (or Command-Shift-O on a mac). Perhaps you could dig into the Eclipse source code (open source) and find the Java code that drives this feature and re-use it. Good luck!
What you are asking for is a tool that will modify your source code outside of the IDE. That's really not a good idea--codegen always ends up sucking, no matter how cool and limited it seems at first.
The only decent case for code generation is where the programmer NEVER sees the intermediate version--this happens with C preprocessor--it makes an intermediate pre-processed version that you never see.
That said, what you might want is something like Groovy. IIRC, groovy allows something like "import *" for import everything.
The thing is, Java is more of a professional tool--you really don't WANT it doing tricky things. Many Java programmers don't even like "import java.util.*" and insist on expanding the exact imports so that you know exactly where each class is coming from.
With lighter languages like groovy, ruby, etc this isn't really as much of a problem--being terse is more important.
PS. If you have to use Java, honestly the answer is no, there is no good solution outside the development environment GUI. Embrace your GUI.
Related
Can I call a static method of another class without using the class name (in the same package)? There are similar questions but all answers there use class names.
Yes. But, you would need to import it. Specifically, import static. Like,
import static com.package.OtherClass.someMethod;
Then you can call someMethod(String) like
someMethod("Like that");
It is possible using static imports, however I would like to caution you against using them. Static imports obfuscate where the code lives which makes it harder to understand the code structure. Combined with * imports, humans can no longer determine (without spending a lot of time) the source of the method, although IDEs can.
An example of why it could be bad: let's say you want to see how a problem was solved in a open source project, to get ideas for your own project. And you know what? You can view the code as HTML online. Things are going great! You view the java file you want to see. Then there is this peculiar method "foo". So you search the page for "foo" and there is exactly 1 match (the one you are looking at). There are multiple import static blabla.* lines at top, so that is a dead end. You download the source. Next you do a full text search on the entire project for "foo(" => 5000 matches in 931 files. At which point you no longer have a choice other than loading the project into an IDE if you want to grok the code. You would not have to do any of that if the author would have made it clear where the method lives to begin with. Now, if you do not use * imports, then finding the class is a 2 step process, so it is not nearly as bad. I personally don't use static imports at all. With short yet meaningful names, I find that the explicit type is preferable.
I dislike static imports, because it breaks OO (well, not technically, just conceptually). But this is a personal opinion and the vast majority disagrees with me. So feel free to form your own. The following post has a great discussion on when (not) to use static imports:
What is a good use case for static import of methods?
Yes it's possible to call static method of a class without using Class reference by using static import.
ex:
import static java.lang.Math.*;
public class compute{
public double getSqrt(double n){
return sqrt(n)
}
}
It's preferable to use this way if static methods are used in lot of places in the class.
I know my question does not seem valid, but it is genuine. When writing java I must use the word import so as to import classes from classpath. It is required to user new to initiate certain objects and other keywords in java. My question is whether we have even the slightest ability to improve and this great language by way of defining new keywords and what they do or modifying the exisiting keyword to do the same thing. For example instead of writing:
import java.io.File;
What possibility is there to modify the import word to bosnian for example:
uvoziti java.io.File;
and it all works the same way. Please do not close before I get ideas.
One approach that uses a rather sophisticated toolchain and could be considered as an "overkill", but is not as much effort as writing an own compiler or so:
Download ANTLR4 from http://www.antlr.org/download.html
Download the Java Grammar at https://github.com/antlr/grammars-v4/blob/master/java/Java.g4
Modify the Java Grammar according to your needs...
Run
java -classpath "antlr-4.4-complete.jar" org.antlr.v4.Tool Java.g4
This will generate some files, one of them being JavaLexer.java.
Create a Java Project that contains the ANTLR JAR and the JavaLexer.java
Create a class like the following, which does the translation:
import java.io.IOException;
import org.antlr.v4.runtime.ANTLRFileStream;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.TokenStream;
public class Main {
public static void main(String[] args) throws IOException {
CharStream s = new ANTLRFileStream("Input.javaX");
JavaLexer lexer = new JavaLexer(s);
TokenStream t = new CommonTokenStream(lexer);
int i = 1;
while (true) {
if (t.LA(i) == -1) {
break;
}
if (t.LA(i) == JavaLexer.IMPORT) {
System.out.print("import ");
} else {
System.out.print(t.LT(i).getText() + " ");
}
i++;
}
}
}
(of course, this is only an example that only translates the IMPORT token, which was defined in the grammar file to be "uvoziti". For a more general and flexible translation, one would define the translation in an external file, and probably read this file to create a map Map<Integer, String> that maps JavaLexer.IMPORT to "import" etc...)
Create the input file from the example: Input.javaX:
uvoziti java.io.File;
public class Input
{
public static void main(String args[])
{
File file = null;
System.out.println("done");
}
}
When you then run the Main, it will read this input file, eventually find the IMPORT token, and instead of the original text (uvoziti) it will print import.
The result will be the contents of a Java file, with an awful formatting...
import java . io . File ; public class Input { public static void main ( String args [ ] ) { File file = null ; System . out . println ( "done" ) ; } }
but fortuntately, the compiler does not care about the formatting: You may write this output directly to a .java file, and the compiler will swallow it.
As it is described here, it is only a proof of concept. For a flexible and generic translation of many (all) keywords, one would have to build some infrastructure around all that. The input files should be read automatically (File.listFiles(), recursively for packages). Each of them would have to be translated (using the Map<Integer, String> that I mentioned earlier). Then the output files would have to be written and compiled, either with the runtime JavaCompiler, or by manually invoking the javac with Runtime#exec.
But in general, I think that this should be doable within a few hours in the best case, and within one week when considering that everything takes longer than you think.
Writing an own Java compiler, on the other hand, might take a bit longer, even when you consider that everything takes longer than you think...
Java doesn't provide any way to redefine keywords.
If you add or remove keywords to the Java language, then it isn't Java anymore.
You could write your own language that compiles to Java. This could be as simple as writing a program that does a string replace of uvoziti for import and then runs it through the javac compiler.
As an option, use something like preprocessor or write your own one, to process java code via replacement of bosnian words to english ones before passing this code to the javac compiler.
I think this approach should work for your case.
Java by itself doesn't help you in this.
You might want to pass your code through a pre-processor, but things start to look a bit crazy: Can I have macros in Java source files.
I've never done something like this, so I'm not sure it will work as intended.
Also, consider that after this change your code is only readable by people understanding bosnian.
You can't really solve this to work generically; java strictly defines the keywords in its language specification and there is no mechanism in the java language to add keywords (e.g. macros).
A partial solution would be to create a preprocessor that translates your new keywords into plain java. Needless to say that this is a pain to integrate into common tool chains and you won't get useful compiler error messages any more for constructs created by the preprocessor.
One step further would be to write your own compiler; again this integrates poorly with existing toolchains. You still don't get proper support from your IDE.
As fascinating as the idea is; the obstacles make it highly impractical for generic use.
The situation is different in languages that come with a compile time macro language (most assembler langauges have this). C's define is another example. They still all have the problem that they are preprocessor based, so added constructs are more complicated (only basic syntax checking etc.)
JVM and JDK understands Java key words. If you want to change into you language, then you have to change JDK and JVM also.
Just use a preprocessor. If java doesn't have one , then write one.
I am a TA for a programming class. There is one assignment in which the students have to write Scala. I am not proficient enough in Scala to read it quickly to verify that the program works or capable of quickly writing a script in Scala to run test inputs.
However, I am very capable in Java. I need some advice on a simple way to grade Scala assignments using my knowledge of Java. Is there a way to load in a Scala file into Java so I could have some simple Java methods to run test inputs for their programs? I am aware of the fact that they both compile to Java byte code, so I figure this should be possible.
Scala generates class files. Scala class files can be run with java, only requiring the scala-library.jar to be on the class path. The entry point on Scala programs appears to Java as a static main method on a class, just like in Java. The difference is that, in a Scala program, that main method is a method declared on an object. For example:
Java:
public class Test {
public static void main(String[] args) {
}
}
Scala:
object Test {
def main(args: Array[String]) {
// or:
// def main(args: Array[String]): Unit = {
}
}
The idea of testing by giving unit tests is interesting, but it will probably force non-idiomatic Scala code. And, in some rare cases, might even prevent the solution to be written entirely in Scala.
So I think it is better to just specify command line arguments, input (maybe stdin), and output (stdout). You can easily run it with either scala Test parms, or java -cp /path/to/scala-library.jar Test parms.
Testing input on individual functions might be a lot harder, though, as they may require Scala classes as input, and some of them can be a bit tough to initialize from Java. If you go that route, you'll probably have to ask many more questions to address specific needs.
One alternative, perhaps, is using Scala expressions from the command line. For example, say you have this code:
object Sum {
def apply(xs: Seq[Int]) = xs reduceLeft (_ + _)
}
It could be tested as easily as this:
dcs#ayanami:~/tmp$ scalac Sum.scala
dcs#ayanami:~/tmp$ scala -cp . -e 'println(Sum.apply(Seq(1, 2, 3)))'
6
To do the same from Java, you'd write code like this:
import scala.collection.Seq$;
public class JavaTest {
static public void main(String[] args) {
System.out.println(Sum.apply(Seq$.MODULE$.apply(scala.Predef.wrapIntArray(new int[] {1, 2, 3}))));
}
}
When you put the .class files generated by the student's code into your classpath, you can simply call the methods which your students developed. With a good Java IDE, you will even have code completion.
Rephrase the question: Assume you have a Java library that you need to test. But you only have the class files, not the source code. How do you do it? - Now, it's exactly the same case with Scala. In some cases, you will need to access strange static variables (such as $MODULE), but that should not be a hindrance. tobym has pointed you in the right direction with his answer.
But seriously, what can be the didactic value for the students? You will only be able to tell them whether or not their programs do the right thing, but you cannot point out to them exactly what mistake they made and how to correct it. They will already know by themselves whether or not their programs are correct. When they made errors, just telling them that they made something wrong won't help them at all. You need to show them exactly where the mistake was made in the code, and how to fix it. This is the only way you can help them learn.
If it is only one assignment and not more, maybe you can find a better way. Maybe you can invite another student who is proficient in Scala to help you out with this. Or maybe you can show some of the erroneous programs to the whole class and initiate a discussion amongst the students, in which they will find out themselves what went wrong and how to correct it. Talking about code in this way can help them a lot, and, if done right, can be a valuable lesson. Because this reflects what they will do later in business life. There won't be a prof telling them how to correct their errors. Instead, they will have to figure it out together with their coworkers. So maybe you can turn this lack of knowledge on your part into an opportunity for your students.
You can compile Scala into a .class file (e.g. "scalac ./foo.scala") and run methods from your Java grading program.
This might be useful reference: How do you call Scala objects from Java?
Well, you could write unit tests (with JUnit, for instance) before the assignment and have the students write the programs to conform to the tests.
Or you could decompile scala to java (with JD-gui, for instance).
But to be fair, if the students are only going to use scala for this one specific assignment, chances are that they are mostly going to translate directly from java to scala, intead of writing idiomatic scala. In that case I'm sure you will be able to understand scala code very easily as it will look almost exactly like java...
You can run
scalac SomeProgram.scala
scala SomeProgram input1
a lot of time during the time it would take to write some java that triggers scala compile and running of the bytecode generated
So I came up with the general idea to write some code in JRuby, then access all the classes via Java. I have no idea if this is at all possible but I wanted to ask anyway. Lets say I
have some JRuby code:
class adder
def addme
return 22
end
end
If I compiled this with jrubyc is there any way I could then possibly do something like this in java:
import adder;
class anything {
void testMethod()
{
adder a = new adder();
int x = a.addme();
}
}
After looking at it now it sort of makes me think that Java will have zero idea what sort of item test addme is going to return so that might not work. I don't know but I wanted to throw it out there anyway.
Thanks
There's actually a new way to do this in JRuby 1.5! Your question is very timely. Here's an example session:
http://gist.github.com/390342
We will hopefully have a blog post detailing this new feature very soon. There's some preliminary docs on the JRuby wiki here:
http://wiki.jruby.org/GeneratingJavaClasses
Actually there are two ways you can call ruby code from java the first is slower but you can change at run time is to invoke the script engine like from this link. but As to how you did it, jrubyc compiles ruby to javaBytecode which means java will see it as java code
jrubyc adder.rb --java
Compiling file "adder.rb" as class "Adder.class"
and just as you've done...
so you would call it like any other java class
import org.jruby.RubyObject
Adder ad = new Adder();
RubyObject ro = ad.addme();
resource
It's possible with the embed package in JRuby, but I think how is beyond the scope of an answer here. Check this out:
http://kenai.com/projects/jruby/pages/RedBridge
I have a jar file. I want to know which external classes and methods are used by classes inside JAR file. Can anyone suggest me any tool?
For example - if below two classes are packaged into Myjar.jar
import java.util.Vector;
class MyJarClass{
public static void main(String args[]){
Vector v = new Vector();
AnotherClass another = new AnotherClass();
v.addElement("one");
another.doSomething();
}
}
class AnotherClass{
void doSomething(){
}
}
When I supply that JAR to a tool - the tool should show java.util.Vector and Vector.adElements() are from external source (not present in MyJar.jar)
Forgot to mention, i don't have access to sourcecode.
Easy
import com.example.*;
Possible
List<com.example.MyType> = new ArrayList<com.example.MyType>();
A challenge
Class<?> clazz = Class.forName("com.example.MyType");
Mission impossible
List<String> classes = getClassNamesFromUrl("http://example.com/classes.txt");
for (String className:classes) {
doSomethingWith(Class.forName(className));
}
I support Jon's advice to look at the byte code (BCEL) but just be aware, that in general it is not possible to read all dependencies from a jar, as they can be dynamic and defined outside the library (see: Mission impossible).
Hard to tell if there's a tool, have a look at those directories on java-source.net:
Open Source ByteCode Libraries in Java
Open Source Code Analyzers in Java (has some applications to work on jars too, like JDepend. JarAnalyzer sounds promising too, but it is quite old, last update in 2005)
Further reading
How can I visualize jar (not plugin) dependencies? (especially VonC's answer)
You might want to look at BCEL, which will allow you to parse the class files and find out what they use. I expect it'll be a certain amount of effort though.
Check untangle
It's a small cli utility that searches usages of class or packages inside jars or directories containing classes.
Disclaimer: I'm the author of untangle
Check JDepend
The graphical user interface displays the afferent and efferent couplings of each analyzed Java package, presented in the familiar Java Swing tree structure.
JavaDepend could help you for such needs, you can for any code elements get all elements used, it can be jar, namespace, class or method.
CQL an SQL like to query code base gives you more flexibility to request any info about your code.