I am looking for a way to programatically get the number of instances of a certain class type in .NET and Java.
Say for example I have class Foo. I want to be able to, in the same process, get a current count of all instance of Foo.
However I cannot modify Foo, so a static int with counting is out. Also I cannot just add all instances I make to some static list and count that. I want to be able to just say:
System.GC.numberOf< Foo >()
or something.
I was looking through the garbage collectors but I could not find any relevant methods.
If you can't modify the class directly (perhaps because it is a built-in class?), could you create a wrapper, or a subclass that inherits the original?
public class subFoo extends foo
{
protected static int count = 0;
public subFoo()
{
count++;
super();
}
protected void finalize() throws Throwable
{
count--;
super.finalize();
}
public static int getInstanceCount()
{
return count;
}
}
This example is Java and may have some syntax issues 'cause I'm a little rusty.
Of course, you'd have to be sure to redeclare all your foo as subFoo throughout the rest of your code.
Another somewhat exotic way to do it would be to use aspect-oriented techniques to instrument the constructor(s) of the class(es) in question. Take a look at AspectJ, for example.
Do you have control of how the Java VM is being run? If so, you can write a quick and dirty debugger agent... http://download.oracle.com/javase/1.5.0/docs/guide/jvmti/jvmti.html#writingAgents
See the events "VM Object Allocation" and "Object Free"
As already commented, there are similar questions in SO.
One hack you can use - a big one IMO - is to change the Object class: see this answer
Resume:
copy the source of Object
add counting to its constructor (finalize)
add method to read the count
prepend the directory with the compiled class to the boot classpath (-Xbootclasspath)
Quick and dirty: if you can't change the class, maybe you can just put a counter in another part of the project, incrementing it when you instantiate said class?
Related
First of all this is not a question about how to implement an interface in Java, or about an error with interfaces. This is a question about the right way to do it, depending on the situation.
First of all i would like to apologize if this is not the correct "stack" to post this question, please let me know and i'll move it to another one.
Let's begin.
What i'm trying to guess is which is the best way to implement an interface in Java. Let's say we have a class A like:
public Class A {
public A(){}
public void fooA() {}
}
And an interface
public interface MyListener {
public void fooListener();
}
Inside fooA() I'm making use of interface B this way:
...
something.setFooListener(/**Doubts here**/)
....
What should we type inside setFooListener(...)
Options are (As far as i know):
A) Define the behavior inside the setFooListener function:
new MyListener.fooListener() {
/** Implementation of fooListener() **/
}
Pros:
Easy and readable as you're reading the function.
You can access directly to FINAL variables defined in fooA().
Cons:
If your implementation is long enough it would end up in a lack of readability and a too long function.
If you're implementing the interface in a few places on the same class you are going to repeat a lot of code.
B) Create an inner class implementing the interface:
private class MyListenerImplementation implements MyListener {
private String var1;
private int var2;
public MyListenerImplementation() {/** constructor **/}
public void fooListener() {
/** Do logic here **/
}
}
Pros:
You can keep a reference to the object MyListenerImplementation.
You can define variables, functions and everything as it's an object like any other one.
Cleaner code.
Cons:
Maybe needs more memory.
Maybe creating unnecessary classes
C) Hold a variable with a reference to the interface implementation
private MyListener.FooListener myListenerVar = new MyListener.FooListener() {
/** Logic goes here **/
};
Pros:
I actually can't sees anyone comparing to B, but a lot of cons.
Cons:
Not a clean code. Doing this on top of your class would be, at least, a war crime.
I don't think it's correct to assign a block of code to a variable.
I don't like how this looks ;)
D) The last one i could think of; define a function and inside return the implementation
private MyListener.fooListener createMyListener() {
return new MyListener.fooListener() {
/** Logic goes here **/
}
}
Pros:
It's cleaner than C.
Reusability
Cons:
Almost the same ones as C.
I don't think it's correct to return a whole block of code.
To sum up: Which i like the most is "B", but i would like to know what does SO thinks of this.
Thanks in advice.
Option A is not syntaxically correct. Your pros and cons are valid.
Option B:
Maybe needs more memory: no.
Maybe creating unnecessary classes: no. Option A also creates a class. It's anonymous, but it's a class, that must be loaded by the ClassLoader like any other class.
Option C: it's exactly the same as A (anonymous class usage), except you initialize a field with the listener. The rule is the same as for any other variable: reduce its scope as much as possible. If you need a field scope, use this option. If you only need the listener in one method, then use a local variable (option A).
Option D: once again, it's the same as A, except you return the created listener instead of only using it.
My recap: you're mixing three orthogonal problems here.
Should I use an anonymous inner class, a named nested class, or a top-level class. This depends on the amount of code contained in the class, and on where you need to use this class: in a single top-level class, or in many top-level classes.
Should I use local variables or instance variables. it's a matter of scope and state, not a matter of interface implementations. Your field or local variable can be initialized with an instance of any kind of your interface implementation
Should you use a factory method returning instances, or should you use new directly. Once again, that has nothing to do with how your interface is implemented. If you want to be loosely coupled, because the factory method might return different implementations of the same interface, use a factory. Otherwise, new is fine.
I was wondering how to achieve the local static variable in java. I know Java wount support it. But what is the better way to achieve the same? I donot want the other methods in my class to access the variable, but it should retain the value across the invocations of the method.
Can somebody please let me know.
I don't think there is any way to achieve this. Java does not support 'local static' a la C, and there is no way to retrofit this while still keeping your sourcecode "real Java"1.
I donot want the other methods in my class to access the variable, but it should retain the value across the invocations of the method.
The best thing would be to make it an ordinary (private) static, and then just don't access it from other methods. The last bit should be easy ... 'cos you are writing the class.
1 - I suppose you could hack something together that involves preprocessing your code, but that will make all sorts of other things unpleasant. My advice is don't go there: it is not worth the pain.
Rather than trying to actually protect the variable, making the code more obscure and complicated, consider logical protection by comment and placement. I declare normal fields at the start of the class, but a field that should only be accessed from one method just before that method. Include a comment saying it should only be used in the one method:
// i should be used only in f
private int i;
/**
* Documentation for f().
*/
public void f(){
System.out.println(i++);
}
What you want is the ability to constraint intermediate computation results within the relevant method itself. To achieve this, you can refer to the following code example. Suppose you want to maintain a static variable i across multiple calls of m(). Instead of having such a static variable, which is not feasible for Java, you can encapsulate variable i into a field of a class A visible only to m(), create a method f(), and move all your code for m() into f(). You can copy, compile, and run the following code, and see how it works.
public class S {
public void m() {
class A {
int i;
void f() {
System.out.println(i++);
}
}
A a = new A();
a.f();
a.f();
a.f();
}
public static void main(String[] args) {
S s = new S();
s.m();
}
}
In theory, yes - but not in conventional manners.
What I would do to create this:
Create that Object in a totally different class, under the private modifier, with no ability to be accessed directly.
Use a debugging tool, such as the JDI to find that variable in the other class, get it's ObjectReference and manipulate directly or create a new variable which references to that object, and use that variable, which references to the object, in your method.
This is quite complicated, as using the JDI is tough, and you would need to run your program on 2 processes.
If you want to do this, I suggest looking into the JDI, but my honest answer would be to look for another solution.
Based on dacongy's idea of using a method local class I created a simple solution:
public class Main {
public static String m() {
class Statics {
static String staticString;
}
if (Statics.staticString == null)
Statics.staticString = "My lazy static method local variable";
return Statics.staticString;
}
}
I know this is a basic question, but I can't find other StackOverflow posts or any good API docs on this.
Say I have an abstract class like Appliance and then I have some classes like Toaster and Blender that extend Appliance. Now suppose that I want to create an ArrayList that will contain mixed elements, all of which are ultimately members of Appliance but could also be Toaster or Blender as well. The Blender class has a method called turnBlenderOff() and the Toaster class has a method called turnToasterOff(), and I will want to iterate over my ArrayList and call these methods, depending on which subclass the element actually belongs to.
Currently I make a class called PowerPoint and try:
// Constructor given an ArrayList of appliances.
public PowerPoint(ArrayList<Appliance> initial_list_of_appliances){
int listSize = initial_list_of_appliances.size();
for(int ii = 0; ii < listSize; ii++){
this.applianceList.add(initial_list_of_appliances.get(ii));
}
}
/////
// Method to switch everything in the list OFF simultaneously.
/////
public void switchOff(){
int N = this.applianceList.size();
String cur_name;
for(int ii = 0; ii < N; ii++){
cur_name = this.applianceList.get(ii).getClassName();
if(cur_name.equals("Blender")){
this.turnBlenderOff(this.applianceList.get(ii));
}
else if(cur_name.equals("Toaster")){
this.turnToasterOff(this.applianceList.get(ii));
}
else if(cur_name.equals("Oven")){
this.turnOvenOff(this.applianceList.get(ii));
}
}
}
Most of my code compiles fine, but I keep getting this error message:
PowerPoint.java:83: turnBlenderOff(appliances.ApplianceWrapper.Blender) in PowerPoint cannot be applied to (appliances.ApplianceWrapper.Appliance)
this.turnBlenderOff(this.applianceList.get(ii));
I see that this method, implemented to work only on Blender objects is trying to be executed on an Appliance object that happens to be a Blender but that the compiler doesn't realize this.
I tried to replace the <Appliance> type with <? extends Appliance> in the ArrayList specifications, but that gave additional errors and would not longer compile.
What is the proper way to make a list based on the abstract type, but then call methods of the subclassed type by using something like getClassName() to retrieve the subclass type?
Added
Since a lot of folks immediately pointed out the obvious: use inheritance better, I need to explain. For this project, we have to assume that all of the subclasses of Appliance were created by third-party people and put into some package that we cannot change. This was done in a bad, crufty way in which all different subclasses have different on/off methods and this can't be changed. So the option of designing a smooth Appliance abstract class is not open to me. For example, Toaster has the method startToasting(), while Oven has the method heatUp(), each of which serves as the 'on' method for the two different classes.
I think the exercise is meant to teach us: how would you retro-fit someone else's bad design job so as to minimize future damage.
If you want to use an abstract class and all subclasses actually have the same functions, why don't you use a function in the abstract base class called "turnDeviceOff" and override it in the subclasses accordingly. That's the OO approach.
The ArrayList is ok.
but you could do this:
public abstract class Appliance{
//declare an abstract method
abstract void switchOff();
}
then
public class Toaster extends Appliance{
//implement the abstract method
void switchOff(){
//do toaster switchOff
}
}
for other subclasses, do the same.
finally,
for(Appliance element: yourList){
element.switchOff();
}
Use instanceof or getClass, not rolling your own getClassName, and then do an explicit cast to the type you just identified.
That said, prefer #guitarflow's answer, though that approach might not work if there is state that you can't just pass to the switchOff method.
There are two ways you can do this. The first (and less-recommended) way is by using the instanceof keyword and casting your Appliance instance into a Blender instance:
for(Appliance a : list){
if(a instanceof Blender) this.turnBlenderOff((Blender)a);
...
}
This is bad because instanceof is slow and doesn't allow you to take advantage of Java's most powerful counterpart to polymorphism, late binding. The better way would be to have the Appliance class have an abstract public method called turnOff(). Then you could do something like:
for(Appliance a : list){
a.turnOff();
...
}
The proper way to solve is by adding a turnOff() method in Appliance class, and have the various subclasses override them appropriately. If you do that, then the big "if" code goes away.
You're rather defeating the point of inheritance: Appliance should define a turnOff() method, which its children should implement appropriately for their needs. That way you can just work with a list of Appliances and not have to worry about what's what.
Otherwise, what's the point of them extending Appliance in the first place?
If you do need to figure out the type of something, use instanceof, testing class names as strings is a terribly brittle way of doing it.
Edit
Random style tip: it's almost never necessary to use index access on Lists anymore:
public PowerPoint(List<Appliance> initialList){
for(Appliance app : initialList)
applianceList.add(app);
}
Of course there's also:
applianceList.addAll(initialList);
Edit 2
A more direct translation:
public void switchOff(){
for(Appliance app : applianceList)
switchOff(app);
}
private void switchOff(Appliance app){
if(app instanceof Blender)
turnBlenderOff(app);
else if(app instanceof Toaster)
turnToasterOff(app);
else if(app instanceof Oven)
turnOvenOff(app);
else
throw new RuntimeException("unknown appliance: " + app);
}
You could also add a wrapper around the different appliance classes that normalizes the API, but it may not be worth it (depending on how involved it is).
A little background first. I am looking into the possibility of implementing Ruby's ActiveRecord in Java as cleanly and succinctly as possible. To do this I would need to allow for the following type of method call:
Person person = Person.find("name", "Mike");
Which would resolve to something like:
ActiveRecord.find(Person.class, "name", "Mike");
The plan is to have Person extend ActiveRecord, which would have a static find method with two parameters (column, value). This method would need to know it was called via Person.find and not another domain class like Car.find and call the find(Class, String, Object) method to perform the actual operation.
The problem I am running into is the finding out via which child class of ActiveRecord the static find method (two param) was called. The following is a simple test case:
public class A {
public static void testMethod() {
// need to know whether A.testMethod(), B.testMethod(), or C.testMethod() was called
}
}
public class B extends A { }
public class C extends A { }
public class Runner {
public static void main(String[] args) {
A.testMethod();
B.testMethod();
C.testMethod();
}
}
Solutions found so far are load-time or compile time weaving using aspectJ. This would involve placing a call interceptor on the testMethod() in A and finding out what signature was used to call it. I am all for load time weaving but the set up of setting this up (via VM args) is a bit complex.
Is there a simpler solution?
Is this at all possible in java or would need to be done in something like groovy/ruby/python?
Would the approach of using something like ActiveRecord.find for static loads and Person.save for instances be better overall?
You cannot override static methods in Java, so any calls to the static method via a subclass will be bound to the base class at compile time. Thus a call to B.testMethod() will be bound to A.testMethod before the application is ever run.
Since you are looking for the information at runtime, it will not be available through normal Java operations.
As others have noted, I don't think the problem is solvable in Java as you pose it. A static method is not really inherited in the same way that a non-static method is. (Excuse me if I'm not using the terminology quite right.)
Nevertheless, it seems to me there are many ways you could accomplish the desired result if you're willing to modify your interface a little.
The most obvious would be to just make the call using the parent class. What's wrong with writing
Person person=(Person)ActiveRecord.find(Person.class, "name", "Mike");
?
Alternatively, you could create an instance of the record type first and then do a find to fill it in. Like
Person person=new Person();
person.find("name", "Mike");
At that point you have a Person object and if you need to know it's class from within a function in the supertype, you just do "this.getClass()".
Alternatively, you could create a dummy Person object to make the calls against, just to let you do the getClass() when necessary. Then your find would look something like:
Person dummyPerson=new Person();
Person realPerson=dummyPerson.find("name", "Mike");
By the way, seems to me that any attempt to have a generic ActiveRecord class is going to mean that the return type of find must be ActiveRecord and not the particular record type, so you'll probably have to cast it to the correct type upon return from the call. The only way to beat that is to have an explicit override of the find in each record object.
I've had plenty of times that I've written some generic record-processing code, but I always avoid creating Java objects for each record type, because that invariably turns into writing a whole bunch of code. I prefer to just keep the Record object completely generic and have field names, indexes, whatever all be internal data and names. If I want to retrieve the "foo" field from the "bar" record, my interface will look something like this:
Record bar=Record.get(key);
String foo=bar.get("foo");
Rather than:
BarRecord bar=BarRecord.get(key);
String foo=bar.getFoo();
Not as pretty and it limits compile-time error-checking, but it's way less code to implement.
You would not do this in Java. You would probably do something more like:
public interface Finder<T, RT, CT>
{
T find(RT colName, CT value);
}
public class PersonFinder
implements Finder<Person, String, String>
{
public Person find(String nameCol, String name)
{
// code to find a person
}
}
public class CarFinder
implements Finder<Car, String, int>
{
public Person find(String yearCol, int year)
{
// code to find a car
}
}
It is possible but it is expensive.
If you can find a way to only call it once then you're set.
You can create a new exception and look at the first frame and then you'll know who call it. Again the problem is it is not performant.
For instance with this answer it is possible to create a logger like this:
class MyClass {
private static final SomeLogger logger = SomeLogger.getLogger();
....
}
And have that logger create a different instance depending on who called it.
So, in the same fashion, you could have something like:
class A {
public static void myStatic() {
// find out who call it
String calledFrom = new RuntimeException()
.getStackTrace()[1].getClassName();
}
}
This is fine for a one time initialization. But not for 1,000 calls. Although I don't know if a good VM may inline this for you.
I would go for AspectJ path.
My theory on this, having built something similar, is to use a code generation strategy to create a delegate for each class which contains the method. You can't have quite as much hidden code in Java, it's probably not worth the effort as long as you generate something reasonable. If you really want to hide it, you could do something like...
public class Person extends PersonActiveRecord
{
}
//generated class, do not touch
public class PersonActiveRecord extends ActiveRecord
{
public Person find(Map params)
{
ActiveRecord.find(Person.class, params);
}
}
But it tends to mess up your inheritance hierarchy too much. I say just generate the classes and be done with it. Not worth it to hide the find method.
You can do it very manually by creating a hackish constructor.
A example = new B(B.class);
And have the superclass constructor store the class that's passed to it.
I don't think the thrown exception above would work, but if you'd want to ever do something like that without creating an exception...
Thread.currentThread().getStackTrace()
You may be able to do it much more smoothly with meta-programming and javassist.
I suppose you want to implement ActiveRecord in Java. When I decided to do the same, I hit the same problem. This is a hard one for Java, but I was able to overcome it.
I recently released entire framework called ActiveJDBC here:
http://code.google.com/p/activejdbc/
If interested, you can look at sources to see how this was implemented. Look at the Model.getClassName() method.
This is how I solved getting a class name from a static method. The second problem was to actually move all the static methods from a super class to subclasses (this is a cludgy form of inheritance after all!). I used Javassist for this. The two solutions allowed me to implement ActiveRecord in Java completely.
The byte code manipulation originally was done dynamically when classes loaded, but I ran into some class loading problems in Glassfish and Weblogic, and decided to implement static bytecode manipulation. This is done by a http: activejdbc.googlecode.com/svn/trunk/activejdbc-instrumentation/ Maven plugin.
I hope this provides an exhaustive answer to your question.
Enjoy,
Igor
Can anyone explain to me why java allows you to access static methods and members from an instance? A bad example, if I have a class called RedShape and it has a static method called getColor() which returns "red", why does java allow you to call the static method from an instance of RedShape? To me this seems to violate some of the core concepts of OO language design. At the least, it should come with a compiler warning.
Thanks in advance.
Edit:
In particular, I'm asking about when you have something like
RedShape test = new RedShape();
test.getColor();
where getColor is a static method of the RedShape class. This doesn't make any sense that it's allowed and doesn't give a compiler warning on the command line via javac. I see that it's "strongly discouraged", but was curious if there was a technical or reasonable reason behind why it's allowed outside of "because C++ allows it."
I don't see anything wrong with calling a static method from an instance. What's wrong with that? In particular, quite often there are methods which are useful within the logic of a class, but which don't actually need to manipulate the instance itself.
I do object to calling a static method via an instance reference. Classic example:
Thread thread = new Thread(...);
thread.sleep(5000); // Doesn't do what it looks like
This comes with a compiler warning in some IDEs - certainly in Eclipse, assuming you turn it on. (Java / Compiler / Errors and Warnings / Code Style / Non-static access to static member.) Personally I consider that a mistake in the design of Java. (It's one of the mistakes that C# managed to avoid copying.)
There's really no reason why you can actually do this.
My only guess was that it would allow you to override static methods, but you can't.
If you try the following scenario:
Banana has a static method called 'test' (this prints 'banana')
Apple extends Banana and "overrides" the static method called 'test' (this prints 'apple')
and you do something like this:
public static void main(String[] args) {
Apple apple = new Apple();
Banana banana = new Banana();
Banana base = new Apple();
apple.test();
banana.test();
base.test();
}
The resulting output is:
apple
banana
banana
So effectively, it's pretty useless.
The access to static methods allows you to share values between instances of the same class or even get the values without needed to create a class instance.
There are cases where it's convenient and is no OO language violation.
I bet it's because the original designers were porting capability from C++, and by the time 20/20 hindsight hit, it was a backwards compatibility issue.
That, or because when you call a method within a class, even though you don't have to prefix everything with this. the compiler inserts it (or equivalent) including for static methods. If static methods couldn't be called from instances, then tacking this. on the front might be a problem (or would force coders to tack class name on the front of static methods whenever they wanted to use them within an actual instance).
Anyway, the answers are speculative unless we get one of the early language developers to answer.
public class MyClass {
public static String myString;
}
public class AnotherClass {
public void doSomething() {
doAnotherThing();
}
public static doAnotherThing() {
MyClass.myString = "something";
}
Here we are accessing static variable from non-static method (indirectly) by calling static method from non static method.