Referencing a new library in Eclipse - java

Please see the attached image:
1) I downloaded a new library here: (http://www.java2s.com/Code/Jar/ABC/Downloadcommonslang24jar.htm)
2) In Eclipse, I right-clicked on 'Referenced Libraries' > Build Path > Configure Build Path > Add External JARs and added 'commons-lang-2.4.jar'
3) I've added import org.apache.commons.lang.* at the top of my class.
4) I entered a method from that class indexOfAny() and get the following error: 'The method indexOfAny() is undefined for the type String.'
What step(s) am I missing? Which steps that I've taken are unnecessary? I need to be able to use this method.
P.S. Pls ignore the rest of the code.

indexOfAny() is NOT a method on a String object.
Maybe you meant to write StringUtils.indexOfAny(...)

You're not using it right, you're trying to invoke the method indexOfAny() on a java.lang.String object - this method is not part of that class. You need to call these methods statically on org.apache.commons.lang.StringUtils - something of the form StringUtils.XXX()
The Commons Library doesn't augment existing classes (in any case, java.lang.String is final). According to the documentation, your call should be something that looks like:
StringUtils.indexOfAny(quantityInForPriceBandPopUp[i], ['z'])
or using one of the overloaded versions.
Update
Is importing the package necessary?
This article and the Java package trail should help with all the details of packages and imports. But some of the basic things to understand are :
Packages are the namespacing mechanism that Java uses - this allows you and I both to write a Utils class while avoiding a collision because of the same name. For example, java.sql.Date and java.util.Date - two Date classes can exist and be used because they're in different packages. It might help to envision packages and their sub-packages as a hierarchy of folders.
Imports are a convenience feature that lets you reference classes by their simple name (Math or String) instead of their fully qualified name (FQN) (java.lang.Math or java.lang.String) every single time you want to use it, which gets painful and clutters up your code, making it much less readable.
Imports don't add anything to your code or make it less efficient since the imported packages aren't linked to your code or anything like that - as mentioned above, it's simply a way to avoid having to use the FQN all the time.
So to answer your question, no, the import is not necessary but then you'd have to use org.apache.commons.lang.StringUtils every single time instead of just being able to use StringUtils. So while not necessary, it's usually convenient both for yourself and anyone else who's going to try to read your code.

You are trying to use these methods on Strings, you should read the documentation of the library you want to use.

Because in documentation you have:
static int indexOfAny(String str, char[] searchChars)
static == you should call this method like this: StringUtils.indexOfAny(...)
String str == put your string here
char[] searchChars == put array of chars which you're searching
Search a String to find the first
index of any character in the given
set of characters.

Related

getting the argument names of a function like netbeans does

Ok, this could be a tricky one. For a code generating tool I need to know methods and arguments of a class. The method name and argument types are the easy ones - just using reflection. But the argument name - and I need the real argument name - is a tricky one because this information is in the javadoc. In my case I use Netbeans 8 and I am pretty sure if Netbeans can get the arguments name I can too. Does anyone know how to read the javadoc to get the argument names of a method?
PS I know this question will pop up. I need the real argument names because the generated code provides an api and it is not very helpful for a developper to use an api where the api methods are something like set_a1, set_a2, and so on.
Indeed, this is tricky, and will involve a considerable effort if you intend to find a general solution that works for arbitrary (third-party) classes and arbitrary Java versions.
However, under certain conditions, there may be a simple solution:
If you can compile the classes on your onw, and if you can use Java 8, then you can use the Method Parameter Reflection infrastructure that was added in Java 8. When compiling the classes with javac -parameters ..., then the parameter names are added to the class file, and can be obtained from the method by calling getParameters on the Method object, and then Parameter#getName()
Parameter parameters[] = method.getParameters();
String name = parameters[0].getName();
...

"Find usages" functionality as an IntelliJ plugin

I'm trying to find a way in IntelliJ IDEA to find all the usages of a few library method calls and classes in a particular project.
The goal is to compile a list of classes which make reference to these specific methods or classes.
How can I go about this, I can see there is a MethodReferencesSearch which looks like it could be helpful, however the search method requires an instance of PsiMethod.
How can I create an instance of PSI method that matches the method in a particular lib class (say I wanted to find all the usages of the concat(...) method in Java's String class
Basically I'm trying to build a plugin that will generate a graph of certain method calls from within a project. For example something that would graph a set of routes by looking for certain method calls in a library. I.e. if Class A calls x(T) with type class B and class B calls x(T) with type of Class C, I would have a graph that looks like A -> B -> C etc. Find usages is great, it just doesnt work well for my needs.
You can get the true PsiMethod by JavaPsiFacade.getInstance(...).findClass("java.lang.String", ...allScope(...)).findsMethodByName("concat", false)[0]. This method can then be passed to MethodReferenceSearch.
I am presuming that you can't guarantee that you have a usage of concat easily available (for example, at the user's cursor position in an open document).
A hacky way to do it would be to create a small, correct, self-contained java class in a String, like below:
class Nothing { String s = "a".concat("b"); }
Then, there is a way (if I remember correctly) to use IntelliJ to parse the class contained in this String, thereby giving you a PsiReference to the method you want to find usages on (in this case, concat).
Would this approach be useful to you?
If so, I can dig out a code example on how this can be done.

How to create a "java.lang.Class" object from a .java file in java

How can I instantiate an object of the class java.lang.Class from a given .java file?
I want to create an application to automatically generate JUnit tests. For that I would need "Method" objects and for "Method" objects I need to have a "Class" object.
java 6 onwards has an api for the compiler: http://www.javabeat.net/2007/04/the-java-6-0-compiler-api/
the link above includes an example.
here's another example - http://www.java2s.com/Code/Java/JDK-6/JavaCompilertoolshowyoucancompileaJavasourcefrominsideaJavaprogram.htm
to load the file once compiled you use a classloader. there's an example at http://tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html and another at http://www.javaworld.com/jw-10-1996/jw-10-indepth.html
you'd think there would be a library to simplify all this. i can't find one, but am still looking.
meanwhile, here's a really nice article from ibm that compiles a function and plots it - http://www.ibm.com/developerworks/java/library/j-jcomp/index.html
found one http://docs.codehaus.org/display/JANINO/Home - this is a library that simplifies the process. i would recommend configuring it to use the javax.tools API (see last sentence in the "what is Janino" paragraph).
sorry for the google snark earlier.
it just struck me that maybe you just want a class object.
if you have a class called MyClass then the associated class is Myclass.class. that's probably obvious, but perhaps that's all you need.
and if you have the class name in a string you can use this method - http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Class.html#forName(java.lang.String)
If you do know the full class String name, why don't you use the Class.forName(className) method to obtain the class Object?
For example, if the class name is yakam.yale.MyClass, just call the
Class.forName("yakam.yale.MyClass");
and the game is played!

Getting the names of all Java classes declared in a package

I'm writing a functionality where it would be helpful to get the classes inside a certain package of my program. Also, I only want the classes that subclass a certain class.
I need the classes in order to call static methods on them.
Is there an automatic way to do this? If so, is it slow?
In case I was not clear, what I want is something like this:
ArrayList<Class<? extends MySuperClass>> classes = ;
classes.add(MyClass.class);
classes.add(MyClass2.class);
Instead of having to call add for each class, I would like to automatically get that class list.
The number of classes is small, so I would not mind declaring them manually if the automatic trick would be slow - this app is for a mobile platform.
In either way, I would also like to know how to call the static method for each method in the ArrayList:
// error The method nameOfStaticMethod is undefined for the type Class<capture#2-of ? extends MySuperClass>
classes.get(0).nameOfStaticMethod ();
Thanks for your comments.
Java doesn't provide this ability. There is no introspection at the package level. The classes could be records in a database, or on the other side of a network connection. There's no requirement for them to be stored and organized so as to facilitate enumerating them by package.
You could make a custom class loader and API to provide a method of listing the class names.
I too would like to list all classes in a package but so far the methods of doing this is pretty bad:
Like JOTN suggested - needs file access - not if it is a jar
Listing a JAR entries - well, also needs the jar file
Quoting a older SO question:
It isn't possible to query a Package for it's Classes (or even its subpackages). http://forums.sun.com/thread.jspa?threadID=341935&start=0&tstart=0 contains a very good discussion about why this is problematic, as well as a handful of solutions to your problem.
Anyways, here is how you invoke static methods on the class:
Method m = Integer.class.getMethod("toString", Integer.TYPE);
System.out.println(m.invoke(null, 123));

Obtaining Java source code from class name

Is there a way to obtain the Java source code from a class name?
For example, if I have access to the library with the class java.io.File, I want its source code.
I am working on a kind of parser and I need the source at execution time. I have also to search it recursively.
Say the aforementioned class has this method:
int method (User user) {...}
I would need to obtain User's source code, and so on and so forth with its inner classes.
Is there any way to obtain the java source from a class name? For example:...
You may want one of several possible solutions. Without knowing what you really want to do with the information, we can't be very precise with our recommendations, but I'd start by steering you away from source code if possible. JSE source code is available online, as are many open source libraries, but that may not always be the case. Additionally, you'll need to keep it all organized when you want to find it, much like a classpath, whereas the Class objects are much easier to get hold of, and manipulate, without having to parse text again.
Reflection
If you just need information about a class at runtime, just use the Java Reflection API. With it, given a Class object you can, for example, get the types of a specific field, list all fields and iterate over them, etc...:
Class clazz = User.class;
Field field = clazz.getDeclaredField("var");
System.out.println(field.getType().getName());
Reflection is useful for discovering information about the classes in the program, and of course you can walk the entire tree without having to find source code, or parse anything.
Remember you can lookup a class object (as long as it's on the classpath at runtime) with Class.forName("MyClass") and reflect on the resulting Class.
Bytecode Manipulation
If you need more than information, and actually want to manipulate the classes, you want bytecode manipulation. Some have tried to generate source code, compile to bytecode and load into their program, but trust me - using a solid bytecode manipulation API is far, far easier. I recommend ASM.
With it, you can not only get information about a class, but add new fields, new methods, create new classes... even load multiple variations of a class if you're feeling self-abusive. An example of using ASM can be found here.
Decompilation
If you really, really do need the source, and don't have it available, you can decompile it from a class object using one of the various decompilers out there. They use the same information and techniques as the above two, but go further and [attempt] to generate source code. Note that it doesn't always work. I recommend Jode, but a decent list, and comparison of others is available online.
File Lookup
If you have the source and really just want to look it up, maybe all you need is to put the .java files somewhere in a big tree, and retrieve based on package name as needed.
Class clazz = User.class;
String path = clazz.getPackage().getName().replaceAll("\\.","/");
File sourceFile = new File(path, clazz.getName() + ".java")
You want more logic there to check the class type, since obviously primatives don't have class definitions, and you want to handle array types differently.
You can lookup a class by name (if the .class files are on your classpath) with Class.forName("MyClass").
You can get a good approximation of the source from a class file using the JAVA decompiler of your choice. However, if you're really after the source of java.io.File then you can download that.
The best and simplest bet can be javap
hello.java
public class hello
{
public static void main(String[] args)
{
System.out.println("hello world!");
world();
}
static public void world()
{
System.out.println("I am second method");
}
}
do a javap hello and you will get this:
Compiled from "hello.java"
public class hello extends java.lang.Object{
public hello();
public static void main(java.lang.String[]);
public static void world();
}
Yes, if you download the source code. It's available for public download on the official download page.
If you're using Eclipse whenever you use the class you could right click > View Source (or simply click the class > F3) and it'll open a new tab with the source.
You can print the resource path from where the class was loaded with
URL sourceURL=obj.getClass().getProtectionDomain().getCodeSource().getLocation();
It will be a .class file , .jar,.zip, or something else.
So what you're trying to do is get the Java class at execution. For this, you need Java reflections.
If your goal is to get information about what's in a class, you may find the Java reflection API to be an easier approach. You can use reflection to look up the fields, methods, constructors, inheritance hierarchy, etc. of a class at runtime, without needing to have the source code for the class available.
Is there any way to obtain the java source from a class name?
The answer is complicated, not least because of the vagueness of your question. (Example notwithstanding).
In general it is not possible to get the real, actual Java source code for a class.
If you have (for example) a ZIP or JAR file containing the source code for the classes, then it is simple to extract the relevant source file based on the classes fully qualified name. But you have to have gotten those ZIP / JAR files from somewhere in the first place.
If you are only interested in method signatures, attribute names and types and so on, then much of this information is available at runtime using the Java reflection APIs. However, it depends on whether the classes were compiled with debug information (see the -g option to the javac compiler) how much will be available. And this is nowhere like the information that you can get from the real source code.
A decompiler may be able to generate compilable source code for a class from the bytecode files. But the decompiled code will look nothing like the original source code.
I guess, if you have a URL for a website populated with the javadocs for the classes, you could go from a class name, method name, or public attribute name to the corresponding javadoc URL at runtime. You could possibly even "screen scrape" the descriptions out of the javadocs. But once again, this is not the real source code.

Categories

Resources