Counter of interface objects in Java - java

In Java, if I want to know how many object of type MyClass, i can define the MyClass in this way
public class MyClass {
public static int count = 0;
public MyClass() {
count++;
}
//other stuff
//...
}
and then, just calling
MyClass.count
I can get the number of objects created.
I am wondering if there's a way to do the same thing with an interface, e.g. if I have my interface called ICountable, how can I know how many objects that are ICountable are there in my program at that moment. I am thinking of doing this with a factory pattern, but in any design way I notice weaknesses, so I haven't come up to a working solution yet, does anyone know a good way to do this?

You could have a look at this thread:
how many instances for a class exists at runtime in java
But I recommend, that you do not implement such a mechanism. There is practically no use case for it in release code. And for debugging / profiling there are several tools. If I remember correctly, the Eclipse profiler keeps track of the instances out of the box, just start it and watch.

Refering to my answer in Get Member/Fields of an existing Object as faar as i know there is no way to guarantee getting all of such informations without parsing the classpath on the file to analyse any .class files or (e.g. static code analysis).
Even if there are classes implementing the desired interface those classes may not be directly visible/ accessable by your Classloaders (anonymous classes for example).
Still in my anser there is a library mentioned that most of the times does the job.

There can be several implementation for single interface. All implementation should consider as type of that interface.
You can try something similar to this.
My interface
public interface Val {}
Implementations
public class Impl1 implements Val {
public Impl1(){
Con.count++;
}
}
.
public class Impl2 implements Val {
public Impl2(){
Con.count++;
}
}
You need to use a global counter here.
Eg:
public final class Con {
static int count;
}
Now any time you can find the count of Val
public static void main(String[] args) {
new Impl1();
System.out.println(Con.count);
new Impl2();
System.out.println(Con.count);
}
you can use separate variables in Impl1 and Impl2 to count each of them separately too.

Related

design an abstract class so that any one can extend it and use the extended class polymorphically

I want to have an abstract class like this:
public abstract Operator {
public int[] operands;
public Operator(int[] operands) {
this.operands = operands;
}
public abstract int getOperatorResult();
}
And some operators to extend from it like:
public class Add extends Operator {
public Add(int[] operands) {
super(operands);
}
public int getOperatorResult() {
return operands[0] + operands[1];
}
}
And an OperatorCreator which gets an expression like "1+1" and returns the appropriate Operator's sub-class(in this case Add):
public class OperatorCreator {
public static Operator getInstance(String expr) {
...
}
}
The main problem:
And I want to let others to design their own operators by extending Operator class. And use their operators polymorphically. something like this:
public class Main {
public static void main(String[] args) {
Operator op = OperatorCreator.getInstance("1-2");
System.out.println(op.getOperatorResult());
}
}
How can I do this?
Edit:
I know it is possible using reflection. But I'd rather not to use reflection if it is possible. And I know I can let the designer of the Operator's sub-class register her new class using invoking a method at runtime. But I don't want to use this method.
Thanks!
Basically you are asking how to implement a framework; in the sense of:
if other parties can provide classes that implement an operator; the main point is: you need a central instance that understands which class provides the implementation for which operator.
So, one solution would be that an "implementer" has to provide a method like "getOperator()" ... which would then return "-", or "+" or whatever.
You could then use reflection to "scan" class files if they implement an interface of yours; and if so; you can call "getOperator()" to understand which class provides which implementation. Later on, your OperationCreator can use that knowledge to instantiate objects of those classes that are required to resolve "1-2" for example.
I would prefer a way that avoids using reflection. Instead, an "implementer" should be able to call some method like "OperationCreator.registerOperationProvider()". Meaning: first, you tell the OperationCreator that object XYZ can handle "-"; then the OperationCreator can dispatch calls for "-" to XYZ later on.
If the main point of the question is how to obtain the implementations at runtime: This is what the ServiceLoader class is for. Implementors then just have to implement the abstract class, and place a file like
META-INF/services/your.packagename.Operator
into their META-INF folder. In this file, they can list their implementations:
their.packagename.MinusOperator
their.packagename.MultiplyOperator
When their code is visible in the classpath of the application (e.g. when it is packaged in a JAR file that is added to the classpath), then you can use the ServiceLoader to easily list all implementations of the Operator class. The JavaDoc of the ServiceLoader class contains an elaborate example showing how this can be done, so I'll omit further example code here (it's really simple).
If the main point of the question was how to use these implementations, referring to the fact that they may need, for example, a method like getOperatorChar() returning - or *, or more broadly: How to create a parser that automatically instantiates these classes, then it should be reworded a bit...

How can I make an Interface Private but used between two classes?

I want to create a private Interface in Class A and have it implemented by Class B. My intention is to have a way for Class A to call a method set on class B that NO ONE else can call. They are in separate file in separate packages. Anyone have any ideas?
The best you can achieve is to give the interface package level visibility and move Class A and B into the same package.
This doesn't stop someone adding another class into the same package in the future, thus giving it access to the interface.
short answer is redesign your class structure.
But if you really need to, consider to use reflex feature in java. and you can inject the method although not recommended.
Disclaimer: not a Java programmer.
But if you want to leverage a type system to get compile-time errors... there are often tricks by introducing a new data type as a sort of "access token" or "dummy parameter". Make it hard to get ahold of a value of that type, but require a value of that type as a parameter in the interface.
Yet introducing a hoop like that winds up being about as contrived as renaming your methods alarming things like DoFooActionOnClassB_ButDontCallUnlessYouAreClassA. I think one usually finds that in a good design, this "dummy type" isn't a dummy type at all... but a capture of the context and state that you should have had in the first place.
I understand that you want to have methods on class B which can only be called from class A. One way would be deferring the real check until runtime but let the compiler make it hard to do the wrong thing. So you could try using a secret which only class A can have in order to protect the method in class B.
public class A {
private static final PrivateA PROOF = new PrivateA();
public static class PrivateA {
private PrivateA() { }
// only A can extend PrivateA
}
public static void main(String[] args) {
new B().methodForAOnly(PROOF, "A");
}
}
Here A's PrivateA is a type which only A can instantiate or extend, and B knows about that...
public class B {
public void methodForAOnly(PrivateA proof, String param) {
if (proof == null) throw new NullPointerException();
// do something
System.out.println(param);
}
}

Understanding the Builder/Factory Pattern

I'm trying to clean up some code I have written for reading data. I have two sources of data: a database and a file. Both currently have separate classes and both classes have optional, non common, parameters in the constructors provided (at the moment traditional telescoping constructors).Both classes Implement interface MyData and when I instantiate the objects I always instantiate a MyData object.
I want to merge these classes into a single class and make the instantiation as clean as possible but I can't figure out how. Im certain its a mixture of builder and factory patterns.The user should never have to see the underlying type MyDatabaseData and MyFileData, just MyData. Can someone help me by sketching out a similar example just to set me off in the right direction
Keep the classes separate since they do different things. Combining them will only make a giant mess and violates the Single Responsibility Principle.
If you don't want the users to see the classes, then make the classes package private.
Then you make a new Builder or Factory class that takes parameters and figures out which class to instantiate.
Hope this helps.
A builder pattern would look like this:
MyDatabaseData data = MyDatabaseData.create()
.authenticate("admin", "rumpelstielchen")
.get();
public class MyDatabaseData {
private MyDatabaseData() { }
public static MyDatabaseBuilder create() {
return new MyDatabaseBuilder(new MyDatabaseData());
}
}
public class MyDatabaseBuilder {
private MyDatabaseData data;
MyDatabaseBuilder(MyDatabaseData data) {
this.data = data;
}
public MyDatabaseData get() {
return data; // Do checks and yield the final result
}
public MyDatabaseBuilder authenticate(String user, String password) {
...
return this; // For chaining calls
}
}
Whether to use common base classes/interfaces is a matter of suitability:
public class MyDatabaseBuilder extends MyBuilder<MyDatabaseData>
However you will probably need to do specific things and hence need child classes. Development not necessarily will become easier, maintaining 4 classes with parallel evolutions.

Is it possible to load one of two different classes in Java with the same name?

I have a lot of code that calls static methods on Foo like "Foo.method()". I have two different implementations of Foo and would like to use one or the other depending on the circumstances. In psuedocode:
File Foo1.java
class Foo1 implements Foo {
public static int method() {
return 0;
}
}
File Foo2.java
class Foo2 implements Foo {
public static int method() {
return 1;
}
}
File Main.java
if(shouldLoadFoo1()) {
Foo = loadClass("Foo1");
} else {
Foo = loadClass("Foo2");
}
Is this possible with Java metaprogramming? I can't quite wrap my head around all the dynamic class loading documentation. If not, what's the best way to do what I'm trying to do?
Essentially you have two classes with the same interface but different implementations,Wouldn't it be better to do it using an interface?
in your main class, depending on the circumstances you would construct your class with the appropriate instance.
FooInterface foo;
MainClass (FooInteface foo, other fields) {
this.foo = foo;
}
....
then just use foo from them on.
Another way is to use AspectJ, define a point cut on every Foo.method call, in in the advice for the point cut have your if (shouldLoadFoo1()) { Foo1.method()} etc ..
The typical approach to exchanging implementations is to use a non-static method and polymorphism, typically using dependency injection to tell the depedent code the implementation to use.
The next cleanest way is the singleton pattern, i.e. to declare:
public abstract class Foo {
protected abstract void doSomeMethod();
// populated at startup using whatever logic you desire
public static Foo instance;
public static void someMethod() {
instance.doSomeMethod();
}
}
The really hacky way to solve your problem would be what you ask for, i.e. to have two different class files for the same class, and decide at runtime which one to use. To do that, you would seperate your project into 4 different jar files:
loader.jar that determines the classpath to use and constructs the classloader for the actual application. The classes in loader.jar must not reference Foo.
foo1.jar that contains one implementation for Foo
foo2.jar that contains another implementation for Foo
common.jar that contains everything else
Loader.jar would then contain a bootstrap method like:
void bootstrap() {
URL commonUrl = // path to common.jar
URL fooUrl;
if (shouldUseFoo1()) {
fooUrl = // path to Foo1.jar
} else {
fooUrl = // path fo Foo2.jar
}
URL[] urls = {fooUrl, commonUrl};
ClassLoader loader = new UrlClassLoader(urls);
Class<?> mainClass = loader.loadClass("my.main");
mainClass.newInstance(); // start the app by invoking a constructor
}
I am not sure I fully understand the problem here (I see many has that issue), but let me try to help.
If your problem was coming down just to using appropriate function method(), you could create a utility function that depending on an instance of a given class will call appropriate method, e.g.
private static int getResultOfFoo(Foo foo)
{
int res = -1;
if(foo instanceof Foo1)
res = Foo1.method();
else res = Foo2.method();
return res;
}
Otherwise, I agree with Stephen C: "Well, see my answer then. That's the closest you are likely to get in Java."
What you have written doesn't make sense from a linguistic standpoint. Foo is an type, and a type is not a variable and cannot appear on the LHS of an assignment. You cannot treat a type as a value in Java ... the language doesn't allow it.
The closest that you can get to what you are trying to do is something like this:
Class fooClass;
if (loadFoo1) {
fooClass = Class.forName("some.pkg.Foo1");
} else {
fooClass = Class.forName("some.pkg.Foo2");
}
Foo foo = (Foo) fooClass.newInstance(); // using the no-args constructor
(I've left out the exception handling ...)
Note that fooClass will be an instance of the class Class which provides runtime handles that are used for performing operations reflectively. We are NOT actually assigning a type. We are assigning an object that "denotes" a type ... in a limited fashion.
HOWEVER ... if you don't need to use dynamic loading you should not use it. In other words, if the underlying problem that you are trying to solve is creating instances of classes that could be statically loaded, then it is better to use the factory pattern; see #andersoj's answer for example.
UPDATE
I just figured out what you are probably trying to do here. That is, you are trying to figure out a way to choose between different static methods (i.e. Foo1.method() and Foo2.method()) without explicitly naming the classes at the point where the call is made.
Again, what you are trying to do simply won't work in Java:
You cannot declare a static method in an interface.
You cannot call a static method in an implementation class via the interface.
Static method calls are not "dispatched" in Java. They are bound statically.
There is a way to do something roughly like this using reflection; e.g.
Class fooClass;
// Load one or other of the classes as above.
Method m = fooClass.getDeclaredMethod("method");
Integer res = (Integer) m.invoke(null);
(As before, I've left out the exception handling)
Once again you would be much better off doing this without resorting to dynamic loading and reflection. The simple approach would be to create a helper method like this in some utilities class:
public static int method() {
return useFoo1 ? Foo1.method() : Foo2.method();
}
Better still, do it the OO way: declare method in the Foo interface as a instance method, create a singleton or an injected instance of Foo1 or Foo2, and rely on polymorphism.
But the take away is that there is NO WAY to avoid changing all of the places in your codebase where method() is called ... if you want to be able to choose between Foo1.method and Foo2.method at runtime.
You can use a factory pattern to do this.
static Foo makeMeAFoo()
{
final Foo foo;
if(shouldLoadFoo1()) {
foo = new Foo1();
} else {
foo = new Foo2();
}
return foo;
}
Which is I think what you're asking for. Though I like hhafez' suggestion better myself.
(Note my answer is now OBE b/c the questioner shifted the methods to be static rather than instance methods. Nevertheless, the tone of other answerers is good... solving this problem by explicit classloading just because you want to select specific static methods is a kludge.)
In your example you in fact have not two different versions of class Foo, but two different implementations of the interface Foo, which is fine in most cases. (They even can exist parallel to each other.)
It is possible to load multiple classes of the same name, but they have to be loaded by different classloaders. This also means that you can't have a third class referencing it by name and then using one or the other (without the third class also being on two classloaders).
Sometimes it may be sensible to have different versions of a class (with same external interface) for different configurations where it would be used (such as "on client side" / "on server side", when some common class in both modules depends on it), and in rare cases you would have both modules in the same VM at the same time - but in most cases it would be better to use the "one interface and multiple implementing classes" approach instead.

Can I use methods of a class without instantiating this class?

I have a class with several methods and there is no constructor among these methods.
So, I am wondering if it is possible to call a method of a class without a creation of an instance of the class.
For example, I can do something like that:
NameOfClass.doMethod(x1,x2,...,xn)
In general I do not see why it should be impossible. I just call a function which does something (or return some values). If it is possible, what will happen if the method sets a value for a private variable of the class. How can I reach this value? In the same way?
NameOfClass.nameOfVariable
It's called static variables and static methods. Just try it and see that it compiles.
If the methods are static, yes.
But you won't be able to access non-static members.
1) YES, you can use the methods of a class without creating an instance or object of that class through the use of the Keyword "Static".
2) If you declare the method as "Static" then you can call this method by :
*ClassName.MethodName()*
3) E.g.
class Hello {
public static void print()
{
System.out.println("HelloStatic");
}
}
class MainMethod {
public static void main(String args[])
{
// calling static method
Hello.print();
}
}
4) The output of the above program would be : HelloStatic
As many have pointed out: This is only possible if the method is static. Maybe some OOP background is in order: A method should always belong to a class. So what is the use of calling a method without an instance of a class? In a perfect OO world there shouldn't be any reason to do that. A lot of use cases that have to do with static methods talk about assigning some kind of identity to your class. While this is perfectly reasonable in a programming world it isn't very convincing when it comes to object oriented design.
As we program in an imperfect world there is often a use case for a "free function" (The way Java or C++ implement sort() for example). As Java has no direct support for free functions classes with only static "methods" are used to express those semantics with the added benefit of the class wrapper providing a "namespace". What you think of this workaround and if you see it as a flaw in language design is IMO a matter of opinion.
In most languages you can do it only if method is static. And static methods can change only static variables.
I have a class with several methods and there is no constructor among these methods.
If you don't explicitly define a constructor then you get a default constructor provided by the compiler. So if those methods aren't static, try this:
NameOfClass x = new NameOfClass();
x.doMethod(x1,x2,...,xn);
A method on a class operates in the context an instance; it has access to the instance's member variables. You understand this, because you ask about what happens if the method accesses one of those variables.
You can understand why it doesn't work by asking yourself the question: "Where is the data?" If you don't have an instance, where is the instance variable? Where is the data? And the answer is that it doesn't have a place and therefore doesn't work.
The difference with a static function and static member variables is that you can answer the question about the location of the data. The static variables available regardless of whether there is a specific instance or not. The instance specific vs. class specific decision is one that you must make considering what you actually want to do.
That would be static methods.
I have a class with several methods
and there is no constructor among
these methods.
Do you mean you have something like:
public class X
{
public void foo()
{
}
}
or do you mean you have something like:
public class X
{
private X()
{
}
public void foo()
{
}
}
If it is the fist way then, yes, there is a constructor and it will look like this:
public X()
{
super();
}
if it is the second way then there is probably a method like:
public static X createInstance()
{
return (new X());
}
If you really mean can classes have methods that do things without ever creating an instance, then yes you can, just make all of the methods and variables static (usually this is not a good idea, but for some things it is perfect).
Since qre is a static method and doesn't have an access to instances of the enclosing class you'll have first to create an instance and then access it. For example:
public class Foo {
private int bar;
public static void qre() {
Foo foo = new Foo();
foo.bar = 5;
System.out.println("next bar: " + (++5));
}
}
In proper encapsulation, you should not "see" what is happening upon instanciation. To rely on a class's lack of a constructor is breaking this form. The designed of the class my have in mind to add formal state initialization in the constructor at a later date. Your "contract" with the class is only that you can use the methods as they are currently designed.
If you desire to use the functionality of that method without the class overhead, maybe it best for you to include that method in your existing "client" class (of course this is just "copy and paste" coding and is considered an anti-pattern of of software design.
If you are using lombok, here is what you can do:
package util;
import lombok.experimental.UtilityClass;
#UtilityClass
public class UtilFunctions {
public static int SumOfTwoNumber(int a, int b){
return a+b;
}
}
In UtilFunctions class here with #UtilityClass annotation, you can keep all the functions which you want to call anywhere in your project. For the sake of simplicity, I have created a function SumOfTwoNumber which I want to use in my main class. Here is how I can call it in the main class:
import util.UtilFunctions;
public class HeadFirstJavaApplication {
public static void main(String[] args) {
int a = 10, b = 20;
int sum = UtilFunctions.SumOfTwoNumber(a,b);
System.out.println(sum);
}
}
P.S: Don't forget to add lombok dependency to be able to use it. In case of gradle, here is how to add the lombok dependency:
dependencies {
compileOnly 'org.projectlombok:lombok:1.18.16'
annotationProcessor 'org.projectlombok:lombok:1.18.16'
testCompileOnly 'org.projectlombok:lombok:1.18.16'
testAnnotationProcessor 'org.projectlombok:lombok:1.18.16'
}

Categories