Encapsulating functions in a second .java file? - java

I've been messing with Android for a couple of weeks, i found many tutorials to follow, but i didnt find anywhere some "Style rules" to make the code looks better.
I would like to know if its possible (im sure that it is, but dont know how to make it xD) to use more .java files to organize the functions. I mean, right now, i have myApp.java where i coded all my application, but is starting to grow so much, so i would like to separate some functions into another .java file.
As i told before, im almost sure that this is possible, but i dont know how to link that second file so, can anybody help me?
Thank you in advance :)

If I understand you correctly you haven't really learned how to use classes in your application? My suggestion is to do a Google search 'Java for beginners' and look for references to Classes and objects.
You normally don't "link" a file in Java as opposed to some other programming languages. In Java you have java files that compile to class files and use them by creating instances of them like so.
MyClass instance = new MyClass();
Where MyClass is defined in a file called MyClass.java (and located in the same package/folder as your main application). If you are unsure about package another Google search can illustrate how to use them.
If you are using Eclipse, it can help you with this. You can create a class and use it by creating a new instance of it in your main application.

You're talking about separation of concerns - you should examine your application design and have classes where the functionality is broken down into logical units per class.
If you're talking about static methods, where you wish to call some functionality which doesn't rely on the state of an object, then perhaps a utility class could be appropriate.
The java.lang.Math is an example, where all the methods on the (final) class are static. Ideally you would just import the methods you'd want to use in your code using the import static keywords.

Related

Can I set up custom warnings in NetBeans

So, I may sound crazy when I say that I want more warnings in my Java code, but hear me out. I'm transitioning to better coding practices, and want the IDE to help. In my older days, I made a library in packages like bht.tools, but now am moving to org.bh.tools. To do this, I'm moving the classes slowly and one-by-one, so that I can also go over their code to make sure best practices are being used there too. This has the added benefit of knowing that any class I import from the new packages has recently been reviewed to be more robust and efficient.
In short, I want NetBeans to show a warning wherever I'm using bht., whether it be in imports, fully-qualified names, etc.. Is this possible?
Yes, you can use the Netbeans Java Hint Module. There is a nice tutorial here.
You probably need do define a TriggerPattern:
Find parts of the source code that satisfy the given pattern, and invoke the method that is annotated with this annotation. The method must be public static, the return type must either be assignable to ErrorDescription or to Iterable. Its sole parameter must be HintContext.
and also a JavaFix
A base class for fixes that modify Java source code. Using this class as a base class makes creating the fix somewhat simpler, but also supports running the hint in the Inspect&Transform dialog. The fix can be converted to Fix by means of the toEditorFix() method.
Read the official tutorial and the org.netbeans.spi.java.hints documentation for full details.

API Creation Inquiry

I am working on a project that needs an API. In most APIs (for example Minecraft Modloader), the API runs the "mod" class, without knowing its name. How is this possible? For this project, I need to get all instances of a class called Spell, without ever calling them directly. All tips and answers are appreciated. Thanks!
I am pretty sure what forge modloader and risu's modloader do is look inside the zips and find any classes with what it needs to be considered a mod class, for example in forge, a #mod annotation. Then it will attempt to load that mod. This is actually how many mods like buildcraft have different parts of the mod in the same zip.

Do I have to use "package" term in every class?

Firstly, I'm trying to learn Java with Java, A Beginner's Guide, 4th Edition. I use Ubuntu as my OS and Netbeans as my IDE. I need to create a project to create a class when using Netbeans.
Here is my hello world app.
class First{
public static void main(String args[])
{
System.out.println("Hello!");
}
}
But this returns a lot of errors. When I put package first; line to top line of my Java class it runs. But, the book isn't using package term. Is this a rule of Netbeans, or what I need to know about this?
You never need to put a class in a package. However, it is almost always a good idea. This is something that Netbeans aggressively tries to encourage you to do.
For small projects, using the default package (that is, a file without a package statement) is OK. However, once your project grows and starts adding external libraries, bad things can happen. What if someone else decided to use the default package and happened to have an identically-named class? Now, since you're both in the same package, collisions can occur!
Your file structure should also reflect your package. That is, a file in package com.myurl.helloworld should be located in a folder called com/myurl/helloworld. This is for the same reasons as above.
Also, and you probably haven't gotten here in your studies, you cannot import classes from the default package, or use the package-private visibility modifier in a default package class.
That's because the author of Java, A Beginner's Guide, 4th Edition most likely used the "default package". This way, you don't have to include any package. A package is a namespace declaration.
What the heck is a namespace declaration!?
A namespace declaration is simply a package which is made to organize your classes. For an instance, if you're going to have multiple classes for, let's say your GUI, and multiple classes for algorithms, blending them together is always a bit confusing. Sorting them in different packages, however is a superior solution.
There is also a naming convention which you should follow if other people are going to look at your code. Packages should be named after a top-level domain. I tend to create SourceForge projects and then I end up with something like this:
net.sourceforge.softwarename.security, net.sourceforge.softwarename.gui, etc...
Also note that you should never use upper case when naming your package. More info here.
You're going to encounter lots of situations like these when learning to programming. They're all a part of the game. You'll just have to figure out a bit by yourself.
The best I can do for you is to recommend Eclipse. Also, when learning Java, I would suggest that you do not use an IDE at ALL! That's because you'll learn to code independently. It's up to you, though.
No you don't need to put in a package into your class UNLESS you are going to import it to another class that will be in it's own file. This is where protected type variables come in when you don't want to make them priviate but only want the subclasses (or child classes) access to them. You are also missing your public statement for your class so it should look like
public class First{
public static void main(String[] args){
System.out.println("Hello!");
}
}
Package represents a directory that contains related group of classes and interfaces.
A package is a namespace that organizes a set of related classes and
interfaces. Conceptually you can think of packages as being similar to
different folders on your computer. You might keep HTML pages in one
folder, images in another, and scripts or applications in yet another.
Because software written in the Java programming language can be
composed of hundreds or thousands of individual classes, it makes
sense to keep things organized by placing related classes and
interfaces into packages.
Below you can find some good discussions regarding java packages:
Java packages com and org
Are there best practices for (Java) package organisation?
Java com.* package namespace

Compile Java class with missing code parts

I'm looking for some ideas on how to compile Java code with some other pieces of code missing (method calls). I am fully aware that javac will not allow you to compile Java files if cannot find all dependencies. But maybe there is some way how to bypass it, something like force compile.
My bytecode knowledge is not so good but I think some method invoke is just full package definition of class and method name with parameters. So if compiler just puts this data to class file and assume in running process dependency will be available (if not simple NoSuchMethodExp).
Only workaround so far I found is to create empty missing class files with empty methods to "cheat" compiler. Works perfectly but there should be easier way :)
Any ideas?
Use Interfaces.
Create the interfaces that have the methods you need. At runtime, inject (Spring, Guice, etc.) or generate (cglib ...) classes that implement the interface.
If you're modifying a jar, you can extract the class files you are not modifying to another directory and include that in the classpath. That way they will be available to the compiler.
Bad luck! Probably all you can do is to create mock objects for missing parts of code just to compile your code (empty methods, so the compiler can find it).
Another question - if you miss some classes, how will you execute that code?
UPDATED according to information provided:
Well, there is another option to modify classes in jar, you can use AOP, and to make it done read about AspectJ - actually for me this is the easiest option (typically you need to spend time mocking objects, writing empty methods, so I would contribute that time to study new technology, which will help you many times ;)
And btw the easiest way to implement it, if you use Eclipse, is:
install AJDT
create aspect project
create aspect which modifies code (depending on what you need to change)
add jar file you want to modify
immediately get modified code in
another already packed jar file
Sounds magically :)
In this case you don't need any dependencies in classpath, except for libraries which are needed for new code you add!
Methods aren't dependencies. They are part of the class definition. The only places the java runtime looks for method definitions is in the class def that was compiled at compile time and in its parent classes. If you're problem is that a super class is incomplete, I don't think I can help you.
If not, you could define some of these methods as abstract and than have a child class implement them.
What kind of code is missing? Normally this happens if you refer to libraries your compiler can't find. Maybe you simply need to extend the classpath the compiler is searching for classes.
If you really refer to code that is not available yet you need to implement at least those methods you refer to. But that sounds strange... maybe you can clear things up.

Is there a way to get all the classes that implement a certain method?

The title speaks for itself. The language is Java.
Yes, there is. This is however a tedious and expensive work. You need to crawl through all class files and all JAR files with help of ClassLoader#getResources() and a shot of java.io.File and load all classes of it with help of Class#forName() and finally check if the method is there by Class#getMethod().
However, there are 3rd party API's which can take the tedious work from hands, but it is still expensive, because loading a class would cause its static initializers being executed.
A cleaner way is to make use of annotations and annotate the methods in question and then make use of libraries which searches for classes/methods/fields based on the annotations, such as Google Reflections.
On the other hand, if the entire package name or the JAR file name is known beforehand, then the work will be less tedious and expensive (no need to do stuff recursively nor to load the all of the classes of entire classpath).
Update: I remember, I ever wrote sample code to achieve something like that, you can find it here. It's good to start with, you only need to change it a bit to check the method.
No, you can't, in general. If you could get a complete list of available classes you could check each of them using reflection - but you can't ask a classloader for a list of everything that's available. (For instance, it may be fetching classes over HTTP, and may not know all the files available.)
If you knew that you were interested in classes in a jar file, however, you could open the jar file, find all the class files within it and ask the classloader for those classes. It would be somewhat fiddly.
What's the bigger picture here? There may be a better way to approach the problem.
Also, in Eclipse, you can simply ask for this :
Clic on the method, and type Ctrl-T.

Categories

Resources