Related
I am 70% confident that this is impossible, but is there a way to make sure that subclasses have a particular constructor or factory method?
In this case, I am trying to create a StringSerializable that would require subclasses to have the following methods
toString, which converts the object to a String.
fromString, which gets an instance from a String.
Obviously, in the first case, I can just make toString abstract. On the other hand, having a nonstatic fromString seems to be problematic. However, I can't create an abstract static method. I also do not think that a constructor is entirely appropriate.
You're correct; it's impossible to force it at compile time. There are various tricks you could do at runtime (such as using reflection in tests), but that's about it.
But ask yourself: why do you want to require that? You can't dynamically invoke a static method or constructor (except through reflection), so how exactly would you use those required factories, if you had them?
If it's just for consistency in the code (which is a good thing!), then you'll just have to ensure that consistency as you develop the code base. A comment in the base class can go a long way here, as can code reviews and other "soft" techniques.
If you plan to use the factories in reflection, then similar reflection can be used in tests to make sure that each subclass has the bits it needs.
Another option is to create a non-static factory:
public interface FooMaker() {
Foo create(String arg);
}
... and use that, rather than a static fromString method.
There again you have the same problem of "how do I ensure that every subclass has a FooMaker implementation?" and again I would say that you shouldn't worry about that. If you make the FooMaker the "starting point" of your code, rather than the subclasses, then it doesn't matter what the subclasses are doing; all that matters is that your FooMakers give you a way of going from string to Foos, and each Foo has a way of going back to a string.
the following code does ensure that every subclass needs to implement the static method, if the subclass does not implement the method it will fail when classes are constructed, as close as you can get to a compile time error, but not at compile time
the exception thrown is very clear and the programm will instantly fail when started
public abstract class Base {
static Functional test;
static {
if(test == null) {
throw new RuntimeException("You need to provide an implementation for the implemntMe method in class base");
}
}
private interface Functional {
Base implementMe(int whatever, boolean anotherParameter);
}
public static void main(final String[] args) {
}
}
the private interface construct ensures that only lambdas can be used to implement the method
a subclass would have to look like this
public SubClass extends Base {
static {
test = (int whatever, boolean anotherParameter) -> {
Subclass tmp = new Subclass();
//construct object
tmp.setWhatever(whatever);
return tmp;
}
}
}
lamdas are like inline methods that implement a functional interface, an interface which has only one abstract method
you can also declare the interface publicly at any other place and implement it with an anonymous inner class,
but my way makes sure that programers have to copy and paste code to reuse it,
or need to copy the object of Functional from another class
Why should we declare an interface inside a class in Java?
For example:
public class GenericModelLinker implements IModelLinker {
private static final Logger LOG =LoggerFactory.getLogger(GenericModelLinker.class);
private String joinAsPropertyField;
private boolean joinAsListEntry;
private boolean clearList;
private List<Link> joins;
//instead of a scalar property
private String uniqueProperty;
public interface Link {
Object getProperty(IAdaptable n);
void setProperty(IAdaptable n, Object value);
}
}
When you want to gather some fields in an object in order to emphasize a concept, you could either create an external class, or an internal (called either nested (static ones) or inner).
If you want to emphasize the fact that this cooperative class makes strictly no sense (has no use) outside the original object use, you could make it nested/inner.
Thus, when dealing with some hierarchy, you can describe a "nested" interface, which will be implemented by the wrapping class's subclasses.
In the JDK, the most significant example would be Map.Entry inner interface, defined within Map interface and implemented by various ways by HashMap, LinkedHashMap etc...
And of course, Map.Entry needed to be declared as public in order to be accessible while iterating the map wherever the code is.
If the interface definition is small and the interface will only be used by clients of the class it's defined in, it's a good way to organize the code. Otherwise, the interface should be defined in its own file.
This is inner interface. Java programming language allows defining inner classes and interfaces. This is typically useful if you want to limit visibility of this class or interface by scope of current outer class.
Some people use this mechanism for creating a kind of namespace. IMHO this is abuse of the language feature (in most cases).
To encapsulate behavior in a generic and resuable way.
Apart from nice example of Map.Entry used by Map implementation classes another good example is implementation of Strategy Pattern, where a execution strategy is evaluated and applied internally.
class Test
{
..
interface Cipher {
doAction();
}
class RAMPCipher implements Cipher{}
class DiskCipher implements Cipher{}
..
}
Inside your class you may need multiple implementations of an interface, which is only relevant to this particular class. In that case make it an inner interface, rather than a public / package-private one.
Only an interface inside a class can be declared private or protected. Sometimes, that makes sense, when the interface is only appropriate for use inside the outer class (or its subclasses).
I am new to Java. One thing confuses me is to why some of the classes need new to instantiate, and why some others do NOT need new to instantiate.
For example, I am looking at log4j, it does not need new.
// get a logger instance named "com.foo"
Logger logger = Logger.getLogger("com.foo");
logger.setLevel(Level.INFO);
Why do some other classes need new? For example, an Employee class:
Employee X = new Employee (John);
X.getwork();
etc etc.
Why we did not say , Logger logger = new Logger(...);? and why were we able to use it even without new, like logger.setLevel(), etc.
The only way to create a new object in Java is with new [1]. However, in some classes, you're not permitted to say new for yourself, you must call a factory method, which might be static (as with your logger example) or not. The author of a class sets this up by making the constructor(s) have access other than public.
Also note that your example may not involve a new object at all. That Logger function might be returning an old object, not a new one.
The following poem by Ogden Nash seems faintly relevant:
This morning I went to the zoo
In order to look at the gnu.
But the old gnu was dead,
and the new gnu, they said,
Was too new a new gnu to view.
[1] Unless you get involved in low-level reflection, or use Object.clone()
In this case, we are dealing with factory methods, as I stated in my comment.
See the relevant API specification on Logger
Retrieve a logger named according to the value of the name parameter. If the named logger already exists, then the existing instance will be returned. Otherwise, a new instance is created.
By default, loggers do not have a set level but inherit it from their neareast ancestor with a set level. This is one of the central features of log4j.
The factory method pattern is a creational design pattern, and, according to Wikipedia, is often useful in the following situations:
The factory pattern can be used when:
The creation of an object precludes its reuse without significant duplication of code.
The creation of an object requires access to information or resources that should not be contained within the composing class.
The lifetime management of the generated objects must be centralized to ensure a consistent behavior within the application.
All three of these are applicable here... who knows what kind of work goes into finding the correct logger? You're not really interested in creating a brand new logger each time you want to use one... instead, your focus is mainly just that -- to use one.
The Creative Commons Wiki also has a relevant article,
Factory methods are sometimes used in place of constructors for any of several reasons:
Some languages (such as Java) do not allow constructors to have useful names
Some languages (such as Java) do not allow constructors to have different names (which may be necessary if you want to use the same method signature for two constructors)
To allow the same instance to be reused instead of recreated each time it is needed (see FlyweightPattern)
I think the third option is probably the most applicable here. Using manual creation of a new Logger, you are unable to adequately share them. Using the getLogger facade enables this to happen transparently.
All in all, the use of factory methods is usually to enable cleaner more straight-forward code without exposing work you don't necessarily care about.
For instance, some classes may prevent you from creating more than one object in the application. It that case you need to call some method for instantiate the class, like the Logger.getLogger(). The getLogger() may have the code like this:
if(uniqueInstance == null) {
uniqueInstance = new Logger();
}
return uniqueInstance;
Where uniqueInstance is an instance of Logger. This is a design pattern called Singleton. In this pattern, you can't instantiate the class because it's constructor is private.
Some other way that you can't instantiate a class is when the class is defined as static.
Classes that have public constructors and aren't static need to be instantiated with the new keyword.
because Logger.getLogger() returns a Logger object. new Logger() calls the constructor which also returns a Logger. This also kind of uses new too, because inside the Logger class is probably something like:
public class Logger {
public static Logger getLogger() {
return new Logger("foo", "bar");
}
}
Well what you are asking is more related to design patterns. The Logger class is following singleton pattern.
Suppose you want that only a single instance of your class gets created accross the application then you can make your constructor private and provide a static method which creates and stores the object of your class when invoked for the first time.
public class SingletonPattern{
private static SingletonPattern instance;
private SingletonPattern(){}
public static synchronized SingletonPattern getInstance(){
if (instance == null){
instance = new SingletonPattern();
}
return instance;
}
}
In this way you can restrict your class to be instantiated only once.
In your example you have to different use cases : the static method that returns an object and the actual constructor call.
The static method is a method that doesn't need to be call on a object, here it's inner mechanism may instantiate an object and return it for futur usage, in this method, there's a call to "new" but the object might be configured, or retrieved from a cache before being return. This is this kind of call
Logger logger = Logger.getLogger("com.foo");
The actual constructor call (which use new) is the normal way to create new object.
You were not technically using the Logger class, but were using a method. You were not technically instantiating the Logger class, nor keeping a reference to it directly as you would with Logger logger = new Logger(). Instead, what you are doing is accessing a method to get back a returned instance. It would be nice to see the class definition. However, more than likely what you have is a static method inside of the class. And the class is more than likely defined with a private constructor. This allows the methods to be accessed without instantiating the class. You can see a good explanation of this, and of static in java here: https://stackoverflow.com/a/1844388/1026459
Some classes cannot be instantiated outside of themselves (e.g. the Math class, these classes have non-public constructors). Of those classes, some provide methods that return instances of the class (e.g. the InetAddress class). These are called factory methods. They are static methods that return instances of the class they're in, so the new keyword need not be used (it is instead used inside of the factory methods). For example:
public class A {
private A() {}
public A createAnA() { return new A(); }
}
Here, createAnA() is the factory method.
It's been about 6 years since I've written Java, so please excuse the rust.
I'm working with a library method that requires that I pass it Class objects. Since I'll have to invoke this method a dynamic number of times, each time with a slightly different Class argument, I wanted to pass it an anonymous class.
However, all the documentation/tutorials I've been able to find so far only talk about instantiating anonymous classes, e.g.:
new className(optional argument list){classBody}
new interfaceName(){classBody}
Can I define an anonymous class without instantiating it? Or, perhaps more clearly, can I create a Class object for an anonymous class?
Unfortunately, there's no way you can dodge the instantiation here. You can make it a no-op, however:
foo((new Object() { ... }).getClass());
Of course, this might not be an option if you have to derive from some class that performs some actions in constructor.
EDIT
Your question also says that you want to call foo "each time with a slightly different Class argument". The above won't do it, because there will still be a single anonymous inner class definition, even if you put the new-expression in a loop. So it's not really going to buy you anything compared to named class definition. In particular, if you're trying to do it to capture values of some local variables, the new instance of your anonymous class that foo will create using the Class object passed to it will not have them captured.
short answer
you cannot (using only JDK classes)
long answer
give it a try:
public interface Constant {
int value();
}
public static Class<? extends Constant> classBuilder(final int value) {
return new Constant() {
#Override
public int value() {
return value;
}
#Override
public String toString() {
return String.valueOf(value);
}
}.getClass();
}
let's creating two new class "parametric" classes:
Class<? extends Constant> oneClass = createConstantClass(1);
Class<? extends Constant> twoClass = createConstantClass(2);
however you cannot instantiate this classes:
Constant one = oneClass.newInstance(); // <--- throws InstantiationException
Constant two = twoClass.newInstance(); // <--- ditto
it will fail at runtime since there is only one instance for every anonymous class.
However you can build dynamic classes at runtime using bytecode manipulation libraries such ASM. Another approach is using dynamic proxies, but this approach as the drawback that you can proxy only interface methods (so you need a Java interface).
You can only reference an anonymous class ONCE. If you do not instantiate it there, you cannot instantiate it since you do not have a name for it.
Hence I believe that anonymous classes can only be used in conjunction with a "new BaseClass()".
In your situation you would pass a BaseClass object to your method doing the work, and instantiate the anonymous object in the source code when you need the object to pass.
You can't access the Class object of an anonymous class without instatiating it. However, if you only need access to the class, you could define local classes within your method and refer to these using the ClassName.class literal syntax.
You can assume the name of an anonymous class and call Class.forName("mypackage.MyBaseClass$1") to get a handle to an anonymous class. This will give you the first anonymous class defined in your MyBaseClass, so this is a rather fragile way to refer to a class.
I suspect whatever you are trying to do could be done a better way. What are you really trying to achieve? Perhaps we can suggest a way which doesn't require you to pass a Class this way.
You can access the class object of an anonymous class by calling .getClass() on it immediately after creation. But what good would that do?
I think the key is in this part of what you said:
I'm working with a library method that requires that I pass it Class
objects.
Why does it want you to pass it Class objects? What does this library do with the Class objects you pass it? Instantiate objects? But if so, what constructor does it use and how does it decide what arguments to pass? I don't know what library you are using or what it does, but I would guess that it always creates objects using the no-argument constructor. However, that will not work for anonymous classes anyway, since they have no public constructor (and in any case, to instantiate any non-static inner class, a reference to the outer instance must be provided, so there is no no-argument constructor).
What's a "static factory" method?
The static factory method pattern is a way to encapsulate object creation. Without a factory method, you would simply call the class's constructor directly: Foo x = new Foo(). With this pattern, you would instead call the factory method: Foo x = Foo.create(). The constructors are marked private, so they cannot be called except from inside the class, and the factory method is marked as static so that it can be called without first having an object.
There are a few advantages to this pattern. One is that the factory can choose from many subclasses (or implementers of an interface) and return that. This way the caller can specify the behavior desired via parameters, without having to know or understand a potentially complex class hierarchy.
Another advantage is, as Matthew and James have pointed out, controlling access to a limited resource such as connections. This a way to implement pools of reusable objects - instead of building, using, and tearing down an object, if the construction and destruction are expensive processes it might make more sense to build them once and recycle them. The factory method can return an existing, unused instantiated object if it has one, or construct one if the object count is below some lower threshold, or throw an exception or return null if it's above the upper threshold.
As per the article on Wikipedia, multiple factory methods also allow different interpretations of similar argument types. Normally the constructor has the same name as the class, which means that you can only have one constructor with a given signature. Factories are not so constrained, which means you can have two different methods that accept the same argument types:
Coordinate c = Coordinate.createFromCartesian(double x, double y)
and
Coordinate c = Coordinate.createFromPolar(double distance, double angle)
This can also be used to improve readability, as Rasmus notes.
NOTE! "The static factory method is NOT the same as the Factory Method pattern" (c) Effective Java, Joshua Bloch.
Factory Method: "Define an interface for creating an object, but let the classes which implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses" (c) GoF.
"Static factory method is simply a static method that returns an instance of a class." (c) Effective Java, Joshua Bloch. Usually this method is inside a particular class.
The difference:
The key idea of static factory method is to gain control over object creation and delegate it from constructor to static method. The decision of object to be created is like in Abstract Factory made outside the method (in common case, but not always). While the key (!) idea of Factory Method is to delegate decision of what instance of class to create inside Factory Method. E.g. classic Singleton implementation is a special case of static factory method. Example of commonly used static factory methods:
valueOf
getInstance
newInstance
We avoid providing direct access to database connections because they're resource intensive. So we use a static factory method getDbConnection that creates a connection if we're below the limit. Otherwise, it tries to provide a "spare" connection, failing with an exception if there are none.
public class DbConnection{
private static final int MAX_CONNS = 100;
private static int totalConnections = 0;
private static Set<DbConnection> availableConnections = new HashSet<DbConnection>();
private DbConnection(){
// ...
totalConnections++;
}
public static DbConnection getDbConnection(){
if(totalConnections < MAX_CONNS){
return new DbConnection();
}else if(availableConnections.size() > 0){
DbConnection dbc = availableConnections.iterator().next();
availableConnections.remove(dbc);
return dbc;
}else {
throw new NoDbConnections();
}
}
public static void returnDbConnection(DbConnection dbc){
availableConnections.add(dbc);
//...
}
}
Readability can be improved by static factory methods:
Compare
public class Foo{
public Foo(boolean withBar){
//...
}
}
//...
// What exactly does this mean?
Foo foo = new Foo(true);
// You have to lookup the documentation to be sure.
// Even if you remember that the boolean has something to do with a Bar
// you might not remember whether it specified withBar or withoutBar.
to
public class Foo{
public static Foo createWithBar(){
//...
}
public static Foo createWithoutBar(){
//...
}
}
// ...
// This is much easier to read!
Foo foo = Foo.createWithBar();
have names, unlike constructors, which can clarify code.
do not need to create a new object upon each invocation - objects
can be cached and reused, if necessary.
can return a subtype of their return type - in particular, can
return an object whose implementation class is unknown to the caller.
This is a very valuable and widely used feature in many frameworks
which use interfaces as the return type of static factory methods.
fromhttp://www.javapractices.com/topic/TopicAction.do?Id=21
It all boils down to maintainability. The best way to put this is whenever you use the new keyword to create an object, you're coupling the code that you're writing to an implementation.
The factory pattern lets you separate how you create an object from what you do with the object. When you create all of your objects using constructors, you are essentially hard-wiring the code that uses the object to that implementation. The code that uses your object is "dependent on" that object. This may not seem like a big deal on the surface, but when the object changes (think of changing the signature of the constructor, or subclassing the object) you have to go back and rewire things everywhere.
Today factories have largely been brushed aside in favor of using Dependency Injection because they require a lot of boiler-plate code that turns out to be a little hard to maintain itself. Dependency Injection is basically equivalent to factories but allows you to specify how your objects get wired together declaratively (through configuration or annotations).
If the constructor of a class is private then you cannot create an object for class from outside of it.
class Test{
int x, y;
private Test(){
.......
.......
}
}
We cannot create an object for above class from outside of it. So you cannot access x, y from outside of the class. Then what is the use of this class?
Here is the Answer : FACTORY method.
Add the below method in above class
public static Test getObject(){
return new Test();
}
So now you can create an object for this class from outside of it. Like the way...
Test t = Test.getObject();
Hence, a static method which returns the object of the class by executing its private constructor is called as FACTORY method.
I thought i will add some light to this post on what i know. We used this technique extensively in our recent android project. Instead of creating objects using new operator you can also use static method to instantiate a class. Code listing:
//instantiating a class using constructor
Vinoth vin = new Vinoth();
//instantiating the class using static method
Class Vinoth{
private Vinoth(){
}
// factory method to instantiate the class
public static Vinoth getInstance(){
if(someCondition)
return new Vinoth();
}
}
Static methods support conditional object creation: Each time you invoke a constructor an object will get created but you might not want that. suppose you want to check some condition only then you want to create a new object.You would not be creating a new instance of Vinoth each time, unless your condition is satisfied.
Another example taken from Effective Java.
public static Boolean valueOf(boolean b) {
return (b ? TRUE : FALSE);
}
This method translates a boolean primitive value into a Boolean object reference. The Boolean.valueOf(boolean) method illustrates us, it never creates an object. The ability of static factory methods to return the same object from repeated invocations allows classes to maintain strict control over what instances exist at any time.
Static factory methods is that, unlike constructors, they can return an object of any subtype of their return type. One application of this flexibility is that an API can return objects without making their classes public. Hiding implementation classes in this fashion leads to a very compact API.
Calendar.getInstance() is a great example for the above, It creates depending on the locale a BuddhistCalendar, JapaneseImperialCalendar or by default one Georgian.
Another example which i could think is Singleton pattern, where you make your constructors private create an own getInstance method where you make sure, that there is always just one instance available.
public class Singleton{
//initailzed during class loading
private static final Singleton INSTANCE = new Singleton();
//to prevent creating another instance of Singleton
private Singleton(){}
public static Singleton getSingleton(){
return INSTANCE;
}
}
A factory method a method that abstracts away the instantiation of an object. Generally factories are useful when you know that you need a new instance of a class that implements some interface but you don't know the implementing class.
This is useful when working with hierarchies of related classes, a good example of this would be a GUI toolkit. You could simply hard-code calls to the constructors for concrete implementations of each widget but if you ever wanted to swap one toolkit for another you'd have a lot of places to change. By using a factory you reduce the amount of code you would need to change.
One of the advantages that stems from Static factory is that that API can return objects without making their classes public. This lead to very compact API. In java this is achieved by Collections class which hides around 32 classes which makes it collection API very compact.
One of the advantages of the static factory methods with private constructor(object creation must have been restricted for external classes to ensure instances are not created externally) is that you can create instance-controlled classes. And instance-controlled classes guarantee that no two equal distinct instances exist(a.equals(b) if and only if a==b) during your program is running that means you can check equality of objects with == operator instead of equals method, according to Effective java.
The ability of static factory methods to return the same object from
repeated invocations allows classes to maintain strict control over
what instances exist at any time. Classes that do this are said to be
instance-controlled. There are several reasons to write
instance-controlled classes. Instance control allows a class to
guarantee that it is a singleton (Item 3) or noninstantiable (Item 4).
Also, it allows an immutable class (Item 15) to make the guarantee
that no two equal instances exist: a.equals(b) if and only if a==b. If
a class makes this guarantee, then its clients can use the == operator
instead of the equals(Object) method, which may result in improved
performance. Enum types (Item 30) provide this guarantee.
From Effective Java, Joshua Bloch(Item 1,page 6)
A static factory method is good when you want to ensure that only one single instance is going to return the concrete class to be used.
For example, in a database connection class, you may want to have only one class create the database connection, so that if you decide to switch from Mysql to Oracle you can just change the logic in one class, and the rest of the application will use the new connection.
If you want to implement database pooling, then that would also be done without affecting the rest of the application.
It protects the rest of the application from changes that you may make to the factory, which is the purpose.
The reason for it to be static is if you want to keep track of some limited resource (number of socket connections or file handles) then this class can keep track of how many have been passed out and returned, so you don't exhaust the limited resource.
Java implementation contains utilities classes java.util.Arrays and java.util.Collections both of them contains static factory methods, examples of it and how to use :
Arrays.asList("1","2","3")
Collections.synchronizedList(..), Collections.emptyList(), Collections.unmodifiableList(...) (Only some examples, could check javadocs for mor methods examples https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html)
Also java.lang.String class have such static factory methods:
String.format(...), String.valueOf(..), String.copyValueOf(...)
static
A member declared with the keyword 'static'.
factory methods
Methods that create and return new objects.
in Java
The programming language is relevant to the meaning of 'static' but not to the definition of 'factory'.