I'm making a testing tool. For this, I need to access a class which is present in Test folder within same project.
I've a class mutant.java in src folder. And I've another class TestAll.java which is present in Test folder within same project. I need to access TestAll.java class in mutant.java class. But I can't be able to find a way to do that.
public void runTest()
{
TestAll a=new TestAll();
}
When I create an object of TestAll.java class in mutant.java class, It gives me an error and didn't recognize that class. I want to access TestAll.java class but don't know How can I?
I need to access TestAll.java class in mutant.java class
No, you need to understand how to properly organize the dependencies within a project.
Your "production" code, that stuff that sits in src is never ever supposed to use something from the test folder. End of story.
Reasoning: src represents the content that you "ship" to your customer. That is your product. Your own test code is not your product. In order to prevent you from (accidentally) releasing "test stuff" to your customer, you ensure that src can't use test. That is why any IDE or build tool organizes your project based on that simple rule.
Thus, the real answer is: you should step back, and rethink what you intend to do. The purpose of any test is to prepare some sort of setup, to then run some production code, and verify the expected behavior.
If your current design prevents that, then, as said: stop right there. Ideally, look out for some peer/tutor to sit down with you and rethink your design, and change it accordingly.
Every second you invest into "how do I use stuff from test within src" is a waste of your energy.
Related
One of the features I like of Eclipse is that when creating Java classes, a wizard is available to specify different properties for the class. Like its package, class to extend from...etc (see below in the screen cap).
Does IntelliJ provide something similar? I created a class but the process wasn't smooth. I had to...mark /java directory as Source Root...create new package...create a new class...and now, I want to extend from a different class other than Object... I would like to avoid doing this step by step, if possible.
I am using IntelliJ Community Edition, version 15.
No, there is no such wizard. Marking the directory as a source root is a one-time action, and is normally taken care of when you create the project. To specify the package, you can enter the package and class name directly in the "New Java class" dialog. If you want to extend a different class, the code completion will help you enter the "extends" or "implements" keyword and specify the base class name.
You can make package at the same time as you create java class.
When you do right click -> new -> java class : at the place of the name you can mark
my.new.package.ClassName and IntelliJ will create the package : my.new.package for you.
For more explication you can visit this page.
In IJ you don't need to write all of this stuff manually. Just right click on the method an choose Go to Test or press Ctrl-Shift-T. This functionality is described on the help page IntelliJ IDEA 15.0 Help /Creating Tests.
In the Create Test dialog:
Select the testing library to be used.
If the selected library is missing in your module, click the Fix button. As a result, the corresponding library will be automatically added to the module libraries.
Define the name and location of the test class to be generated.
In the Class name field, specify the name of the stub test class to be generated.
In the Superclass field, IntelliJ IDEA suggests the appropriate super class for JUnit3. For JUnit 4 and TestNG, this field is blank.
In the Destination package field, define where the generated test class should be placed.
Specify whether you want the setUp()/tearDown() methods (for JUnit), or the #Before/#After annotations to be generated.
In the table that shows the list of all the methods of the source class, select the ones you want to generate test methods for.
Click OK.
In addition to other answers if you hit Alt-Enter on any interface or abstract class name one of the intention options will be to create an implementation.
I read somewhere that all Java code I write should be under the com.my.package (just an example) in the src folder. Is this true? I really don't want to clutter that space with tons of java files (especially the crucial ones like activities, fragments, etc.).
Examples of code I want to place somewhere: A class that takes care of UI Fading, a class that validates emails, etc. I was thinking of putting them under libs, but I was told that is for external libraries not written by me.
just add a new package (ie a sub folder). something like com.my.package.mystuff or com.my.package.utils or something similar. That way you can keep your code separated.
you should be putting them in the main source folder as you said. However, you can have subpackages to avoid things becoming too cluttered. (com.my.package.sub.MyClass). One common pattern I've observed in Google apps is putting activities/fragments in a UI package to keep them clear from the rest of the code.
Make additional packages to organize your files. Typically all of your code should live at least under com.my.package, but not necessarily at that level. For example:
com/my/package
com/my/package/utils
com/my/package/fragment
You can organize it just like any directory structure. There are differences though, since if you have package private fields (e.g. String x instead of private String x they will not be accessible to classes outside of the same package).
I've always wanted to write a simple world in Java, but which I could then run the 'world' and then add new objects (that didn't exist at the time the world started running) at a later date (to simulate/observe different behaviours between future objects).
The problem is that I don't want to ever stop or restart the world once it's started, I want it to run for a week without having to recompile it, but have the ability to drop in objects and redo/rewrite/delete/create/mutate them over time.
The world could be as simple as a 10 x 10 array of x/y 'locations' (think chessboard), but I guess would need some kind of ticktimer process to monitor objects and give each one (if any) a chance to 'act' (if they want to).
Example: I code up World.java on Monday and leave it running. Then on Tuesday I write a new class called Rock.java (that doesn't move). I then drop it (somehow) into this already running world (which just drops it someplace random in the 10x10 array and never moves).
Then on Wednesday I create a new class called Cat.java and drop that into the world, again placed randomly, but this new object can move around the world (over some unit of time), then on Thursday i write a class called Dog.java which also moves around but can 'act' on another object if it's in the neighbour location and vice versa.
Here's the thing. I don't know what kinda of structure/design I would need to code the actual world class to know how to detect/load/track future objects.
So, any ideas on how you would do something like this?
I don't know if there is a pattern/strategy for a problem like this, but this is how I would approach it:
I would have all of these different classes that you are planning to make would have to be objectsof some common class(maybe a WorldObject class) and then put their differentiating features in a separate configuration files.
Creation
When your program is running, it would routinely check that configuration folder for new items. If it sees that a new config file exists (say Cat.config), then it would create a new WorldObject object and give it features that it reads from the Cat.config file and drops that new object into the world.
Mutation
If your program detects that one of these item's configuration file has changed, then it find that object in the World, edit its features and then redisplay it.
Deletion
When the program looks in the folder and sees that the config file does not exist anymore, then it deletes the object from the World and checks how that affects all the other objects.
I wouldn't bet too much on the JVM itself running forever. There are too many ways this could fail (computer trouble, unexepected out-of-memory, permgen problems due to repeated classloading).
Instead I'd design a system that can reliably persist the state of each object involved (simplest approach: make each object serializable, but that would not really solve versioning problems).
So as the first step, I'd simply implement some nice classloader-magic to allow jars to be "dropped" into the world simulation which will be loaded dynamically. But once you reach a point where that no longer works (because you need to modify the World itself, or need to do incompatible changes to some object), then you could persist the state, switch out the libraries for new versions and reload the state.
Being able to persist the state also allows you to easily produce test scenarios or replay scenarios with different parameters.
Have a look at OSGi - this framework allows installing and removing packages at runtime.
The framework is a container for so called bundles, java libraries with some extra configuration data in the jars manifest file.
You could install a "world" bundle and keep it running. Then, after a while, install a bundle that contributes rocks or sand to the world. If you don't like it anymore, disable it. If you need other rocks, install an updated version of the very same bundle and activate it.
And with OSGi, you can keep the world spinning and moving around the sun.
The reference implementation is equinox
BTW: "I don't know what kinda of structure/design" - at least you need to define an interface for a "geolocatable object", otherwise you won't be able to place and display it. But for the "world", it really maybe enough to know, that "there is something at coordinates x/y/z" and for the world viewer, that this "something" has a method to "display itself".
If you only care about adding classes (and not modifying) here is what I'd do:
there is an interface Entity with all business methods you need (insertIntoWorld(), isMovable(), getName(), getIcon() etc)
there is a specific package where entities reside
there is a scheduled job in your application which every 30 seconds lists the class files of the package
keep track of the classes and for any new class attempt to load class and cast to Entity
for any newlly loaded Entity create a new instance and call it's insertIntoWorld().
You could also skip the scheduler and automatic discovery thing and have a UI control in the World where from you could specify the classname to be loaded.
Some problems:
you cannot easily update an Entity. You'll most probably need to do some classloader magic
you cannot extend the Entity interface to add new business bethod, so you are bound to the contract you initially started your application with
Too long explanation for too simple problem.
By other words you just want to perform dynamic class loading.
First if you somehow know the class name you can load it using Class.forName(). This is the way to get class itself. Then you can instantiate it using Class.newInstance(). If you class has public default constructor it is enough. For more details read about reflection API.
But how to pass the name of new class to program that is already running?
I'd suggest 2 ways.
Program may perform polling of predefined file. When you wish to deploy new class you have to register it, i.e. write its name into this file. Additionally this class has to be available in classpath of your application.
application may perform polling of (for example) special directory that contains jar files. Once it detects new jar file it may read its content (see JarInputStream), then call instantiate new class using ClaasLoader.defineClass(), then call newInstane() etc.
What you're basically creating here is called an application container. Fortunately there's no need to reinvent the wheel, there are already great pieces of software out there that are designed to stay running for long periods of time executing code that can change over time. My advice would be to pick your IDE first, and that will lead you someways to what app container you should use (some are better integrated than others).
You will need a persistence layer, the JVM is reliable but eventually someone will trip over the power cord and wipe your world out. Again with JPA et al. there's no need to reinvent the wheel here either. Hibernate is probably the 'standard', but with your requirements I'd try for something a little more fancy with one of the graph based NoSQL solutions.
what you probably want to have a look at, is the "dynamic object model" pattern/approach. I implemented it some time ago. With it you can create/modify objecttypes at runtime that are kind of templates for objects. Here is a paper that describes the idea:
http://hillside.net/plop/plop2k/proceedings/Riehle/Riehle.pdf
There are more papers but I was not able to post them, because this is my first answer and I dont have enough reputation. But Google is your friend :-)
While developing Eclispe plugin, I am able to programmatically rename a class-field using the following code.
RenameSupport renameSupport = RenameSupport.create(field, newName, RenameSupport.UPDATE_REFERENCES);
renameSupport.perform(workbench.getShell(), workbench);
But it applies the changes to the actual source files. Is there anyway that can be prevented? I just need the renamed code internally (for performing some other computations), must not change the actual source.
Please suggest.
You could copy it into a temporary file with File.createTempFile() and then rename the code in your temporary file, if RenameSupport lets you do that. If it doesn't, then you can copy the original to a temporary file and copy it back once your other computations are finished.
First, create an instance of RefactoringDescriptor. Then, invoke createRefactoring on it to create an instance of Refactoring. You can get the change object by invoking createChange on the Refactoring object. The Change object will tell you how the refactoring is going to change the code. Finally, you can invoke the method perform on the Change object to apply it on the underlying files.
The plugin org.eclipse.jdt.ui.tests.refactoring contains automated unit tests for Java refactorings in Eclipse. For a concrete example of how to invoke a refactoring programmatically, refer to org.eclipse.jdt.ui.tests.refactoring.RefactoringTest.
This seems like it should be fairly straight-forward, but I can't see anything obvious. What I basically want to do it to point at a method and refactor->extract class. This would take the method in question to a new class with that method as top level public API. The refactoring would also drag any required methods and variables along with it to the new class, deleting them from the old class if nothing else in the old class is using it.
This is a repetitive task I often encounter when refactoring legacy code. Anyway, I'm currently using Eclipse 3.0.2, but would still be interested in the answer if its available in a more recent version of eclipse. Thanks!
I don't think this kind of refactoring exists yet.
Bug 225716 has been log for that kind of feature (since early 2008).
Bug 312347 would also be a good implementation of such a refactoring.
"Create a new class and move the relevant fields and methods from the old class into the new class."
I mention a workaround in this SO answer.
In Eclipse 3.7.1 there is an option to move methods and fields out of a class. To do so:
Make sure the destination class exists (empty class is fine, just as long as it exists in the project).
In the source class, select the methods that you want to remove (the outline view works great for this), right click on the selection, and choose Move
Select the destination class in the drop down/Browse
Your members are now extracted. Fix any visibility issues (Source > Generate Getters and Setters is very useful for this) and you are all set.
This seems like it should be fairly
straight-forward...
Actually, Extract Class is one of the more difficult refactorings. Even in your simple example of moving a single method and its dependencies, there are possible complications:
If the moved method might be used in code you don't know about, you need to have a proxy method in the original class that will delegate to (call) the moved method. (If your application is self-contained or if you know all the clients of the moved method, then the refactoring code could update the calling code.)
If the moved method is part of an interface or if the moved method is inherited, then you will also need to have a "proxy method".
Your method may call a private method/field that some other method calls. You need to choose a class for the called member (maybe in the class that uses it the most). You will need to change access from "private" to something more general.
Depending on how much the original class and the extracted class need to know about each other, one or both may need to have fields initialized that point to the other.
Etc.
This is why I encourage everybody to vote for bug 312347 to get fixed.
Have you tried the Move feature of the Refactor group ? You can create a helper class and move there anything you want.