Java Proxy.newProxyInstance IllegalArgumentException - java

I define an interface follow
interface SdkInterface {
void onPause();
void onResume();
void onStop();
}
then I define a abstract class implement the interface
abstract class BaseCore implements SdkInterface {
public static final byte[] lock = new byte[0];
private static final String TAG = "BaseCore";
public static Core instance;
#Override
public void onPause() {
Log.e(TAG, "onPause: ");
}
#Override
public void onResume() {
Log.e(TAG, "onResume: ");
}
#Override
public void onStop() {
Log.e(TAG, "onStop: ");
}
}
then I has a class extends the abstract class
class Core extends BaseCore {
private Core() {
}
public static Core getInstance() {
if (instance == null) {
synchronized (lock) {
if (instance == null) {
instance = new Core();
}
}
}
return instance;
}
}
now I want to generate a proxy for the instance field of the BaseCore class,I do this
public static void register() {
try {
Class<?> core = Class.forName("com.secoo.coobox.Core");
Field instance = core.getSuperclass().getDeclaredField("instance");
Method getInstance = core.getDeclaredMethod("getInstance");
Object invoke = getInstance.invoke(null);
Object o = Proxy.newProxyInstance(core.getClassLoader(), core.getInterfaces(), new InvocationHandler() {
#Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Log.e("BaseCore", "invoke: before " + method.getName());
Object invoke1 = method.invoke(invoke, args);
Log.e("BaseCore", "invoke: after " + method.getName());
return invoke1;
}
});
instance.set(invoke, o);
} catch (ClassNotFoundException | NoSuchFieldException | NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
but I receive the exception
Caused by: java.lang.IllegalArgumentException: field com.secoo.coobox.BaseCore.instance has type com.secoo.coobox.Core, got $Proxy2
at java.lang.reflect.Field.set(Native Method)
at com.secoo.coobox.TestProxy.register(TestProxy.java:31)
at com.secoo.coobox.MainActivity.onCreate(MainActivity.kt:24)
at android.app.Activity.performCreate(Activity.java:8006)
at android.app.Activity.performCreate(Activity.java:7990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1329)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3584)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3775) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2246) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:233) 
at android.app.ActivityThread.main(ActivityThread.java:8010) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:631) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:978) 
who can help me explain the excetion and how I can solve the problem? thanks

Your code has serious style issues, and it is broken. And we haven't even gotten to the error you're asking about yet. I suggest you skip the actual answer and instead read why you're barking up the wrong tree and need to rethink this code, making the actual answer irrelevant for you.
The actual answer
Proxy will make a new instance of a proxy class (that's where that $Proxy2 thing is coming from). Proxy cannot make an object that is an instance of that actual class: That's just not how java works. Thus, you have an instance of an unknown, effectively irrelevant class. However, that $Proxy2 class does implement whatever interfaces you want it to. It can't extend anything (other than, obviously, java.lang.Object). No final classes, no normal classes, not even abstract classes. That's just how it works: If you want a proxy that extends something specific, you're out of luck.
Thus: You can only proxy interfaces.
Had the field been:
public static SdkInterface instance;
instead, it would have worked fine; That $Proxy2 class is a class made on the fly by the Proxy.newProxyInstance call, and this class implements all the interface you passed in.
But, as I said, do not just start changing things, you need to rethink this code more fundamentally.
The more significant issues with your code
Your BaseCore class has a field of type Core, eliminating any point or purpose in the class hierarchy of it. Its type should possible be BaseCore, or the 'singleton holder' field should be in Core. Generally fields should have the least specific type that you want to use, e.g. we write List x = new ArrayList - because List is less specific. You've gone the other way, and made the field the most specific type you could find (Core, which is more specific than BaseCore, which is more specific than SdkInterface). If that static field's type is SdkInterface, you can assign a proxy object to it. But if the type of that field is a class (other than java.lang.Object), then that is impossible - as proxies implement whatever interfaces you want, but extend j.l.Object and can't be made to extend anything else.
Double checked locking does not work, so don't do it. Your getInstance() method is broken in a really nasty way: It is broken, but, most tests do not catch it. It requires a specific combination of hardware, android version, and phase of the moon for it to fail. There are only 2 sane ways to 'load' singletons: Generally, just initialize the field (and make it final), because java lazy loads; the only benefit to having an actual method that loads it only when you invoke .getInstance() or whatnot, is when it is plausible you will 'touch' the class (load a class that has a field of type Core, for example), but never actually need the instance. This happens, but it is rare. If it doesn't apply to you, there is no point to any of this, and you can just write public static final Core INSTANCE = new Core(); and be done with it all. If you really do need the getSingleton method, use the java classloader which is extremely good at efficient locking - at least as good as anything you can write in java and possibly better:
public static Core get() {
return CoreSingletonHolder.INSTANCE;
}
private static class CoreSingletonHolder {
static final Core INSTANCE = new Core();
}
This works because java doesn't load classes until it is needed, and nothing 'touches' CoreSingletonHolder (causing it to be loaded), except invoking the get() method. Hence, new Core() is executed exactly once, and only once, as per JVM guarantees, using ClassLoader's own locking mechanism, which is very efficient. It's efficient because java has to do this with every single last class your app ever loads. If it wasn't efficient, java/android would be dog slow, and we know it isn't, QED.
Your intended singleton instance is public and non-final; anything can overwrite it. The above strategies fix these issues; given that all access needs to go through get() in order to ensure its initialized, why make it public?

Related

How to implement a subclassable Singleton in Java

I am looking for a way to implement an abstract class (or effectively abstract) that enforces only one instance of each subclass.
I am fairly sure this would be pretty simple to implement with a Factory but I would be interested to know if it can be done without knowing all subclass types, i.e a generic singleton enforcer class.
Right now I am mostly just playing around with the idea for something like this, So I am not looking for feedback that questions the design choice here.
The language I am working in is Java, but right now I am not necessarily worried about implementation details, Unless it is not possible in Java, then, of course, provide evidence that it is not possible.
I'm wondering what it is you are trying to do. A couple of possibilities spring to mind and knowing where this is heading might help.
Option 1
So you could try to use an enum type as your abstract base class. Each enumeration constant is then guaranteed by the language to be a singleton. The enum can have abstract methods which the constants implement. This will work but compilation unit an get very big and hard to navigate if you have a lot of implementing constants and a lot of abstract methods to implement. You could of course delegate some of the work to helper classes if it starts to get out of hand.
Option 2
You could do is get the base class constructor to check it's actual type and store it in a static HashSet (or similar). If an entry already exists then you have two instances of the same singleton. Something like
public abstract class BaseClass {
private static HashSet<Class<?>> instances = new HashSet<>();
protected BaseClass() {
checkInstances();
}
private synchronized void checkInstances() {
boolean duplicate = instances.add(getClass());
if (duplicate) {
throw new RuntimeException("Duplicate class " + getClass().getName());
}
}
}
The disadvantage of this is that the error occurs at runtime and the code isn't especially pretty and as you can see you may need to consider synchronization of the set
Option 3
Your final option is simply not to ask the base class to enforce this restriction. It should probably the job of the derived classes to decided if they are singletons or not. A private constructor in the derived class is the easiest way to do that.
Conclusion
Personally I'd implement either option 1 or option 3 as you won't get run-time failures.
First, a generic singleton doesn't make sense.
A parent class should not be responsible of retrieving and managing instances of its subclasses.
It creates a strong coupling in both ways (parent->child and child->parent).
Second, as shmosel says, subclassing a singleton (without special artifact) is not possible.
The key of the singleton pattern is the lack of ability to instantiate the class outside the singleton class, so no public constructor has to be provided.
In these conditions, how subclass the singleton class ?
To allow subclassing a singleton class, you must have a public constructor while ensuring that you have no more than one instance of the class.
Inversion of control containers such as Spring may do that (It is an example of special artifact).
As a side note, I don't consider access modifier tweaking such as the package-private modifier that could allow to subclass a singleton but the limitation of it is that the singleton would be a singleton only outside the package.
I wanted to say, that singletons are bad. But found this problem interesting, So I created what you want.
Here is the code
public static abstract class SingletonBase {
private static HashSet<SingletonBase> instances = new HashSet<>();
{
for (SingletonBase sb : instances) {
if (sb.getClass() == this.getClass()) throw new RuntimeException("there is already 1 instance");
}
}
public static <E> E getInstance(Class<E> clazz) {
if (!SingletonBase.class.isAssignableFrom(clazz)) {
throw new RuntimeException();
}
for (SingletonBase sb : instances) {
if (sb.getClass() == clazz) return (E) sb;
}
try {
return clazz.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
private SingletonBase() {
instances.add(this);
}
}
static class SingletonTest extends SingletonBase{
}
static class SecondSingletonTest extends SingletonBase{
}
public static void main(String[] args) {
for(int i=0;i<=10;i++)
System.out.println( SingletonBase.getInstance(SingletonTest.class));
for(int i=0;i<=10;i++)
System.out.println( SingletonBase.getInstance(SecondSingletonTest.class));
//throws exception, because we try to create second instance here
new SingletonTest();
}
There are some problems with approach of creating generic class which are solved here:
first, you cannot create more than one instance, so base class has to keep track of all instances, and when you try to create another one using new, it will throw exception. Second, you need to get instance for a specific class. If you dont want to create instance like this:
SingletonBase.getInstance(SecondSingletonTest.class)
You can create subclasses like this:
static class SingletonTest extends SingletonBase{
public static SingletonTest getInstance(){
return getInstance(SingletonTest.class);
}
}
There was also suggested to use ENUM approach, it is easy to implement, but breakes open closed principle from SOLID

Default method in interface in Java 8 and Bean Info Introspector

I have a little problem with default methods in Interface and BeanInfo Introspector.
In this example, there is interface: Interface
public static interface Interface {
default public String getLetter() {
return "A";
}
}
and two classes ClassA and ClassB:
public static class ClassA implements Interface {
}
public static class ClassB implements Interface {
public String getLetter() {
return "B";
}
}
In main method app prints PropertyDescriptors from BeanInfo:
public static String formatData(PropertyDescriptor[] pds) {
return Arrays.asList(pds).stream()
.map((pd) -> pd.getName()).collect(Collectors.joining(", "));
}
public static void main(String[] args) {
try {
System.out.println(
formatData(Introspector.getBeanInfo(ClassA.class)
.getPropertyDescriptors()));
System.out.println(
formatData(Introspector.getBeanInfo(ClassB.class)
.getPropertyDescriptors()));
} catch (IntrospectionException e) {
e.printStackTrace();
}
}
And the result is:
class
class, letter
Why default method "letter" is not visible as property in ClassA? Is it bug or feature?
I guess, Introspector does not process interface hierarchy chains, even though with Java 8 virtual extention methods (aka defenders, default methods) interfaces can have something that kinda sorta looks like property methods. Here's a rather simplistic introspector that claims it does: BeanIntrospector
Whether this can be considered a bug is somewhat of a gray area, here's why I think so.
Obviously, now a class can "inherit" from an interface a method that has all the qualities of what's oficially considered a getter/setter/mutator. But at the same time, this whole thing is against interface's purpose -- an interface can not possibly provide anything that can be considered a property, since it's stateless and behaviorless, it's only meant to describe behavior. Even defender methods are basically static unless they access real properties of a concrete implementation.
On the other hand, if we assume defenders are officially inherited (as opposed to providing default implementation which is a rather ambiguous definition), they should result in synthetic methods being created in the implementing class, and those belong to the class and are traversed as part of PropertyDescriptor lookup. Obviously this is not the way it is though, otherwise the whole thing would be working. :) It seems that defender methods are getting some kind of special treatment here.
Debugging reveals that this method is filtered out at Introspector#getPublicDeclaredMethods():
if (!method.getDeclaringClass().equals(clz)) {
result[i] = null; // ignore methods declared elsewhere
}
where clz is a fully-qualified name of the class in question.
Since ClassB has custom implementation of this method, it passes the check successfully while ClassA doesn't.
I think also that it is a bug.
You can solve this using a dedicated BeanInfo for your class, and by providing somthing like that :
/* (non-Javadoc)
* #see java.beans.SimpleBeanInfo#getAdditionalBeanInfo()
*/
#Override
public BeanInfo[] getAdditionalBeanInfo()
{
Class<?> superclass = Interface.class;
BeanInfo info = null;
try
{
info = Introspector.getBeanInfo(superclass);
}
catch (IntrospectionException e)
{
//nothing to do
}
if (info != null)
return new BeanInfo[] { info };
return null;
}
This is because you only have your method on Interface and ClassB, not on ClassA directly. However it sounds to me like a bug since I'd expect that property to showup on the list. I suspect Inrospector did not catch up with Java 8 features yet.

How do I reduce delegation boilerplate?

I have a class that implements an interface. There's another class that implements this interface, too, and an instance of this second class backs my class's implementation.
For many of the methods specified by the interface, my class simply forwards them straight to the second class.
public class MyClass implements MyInterface
{
private OtherClass otherClassInstance; // Also implements MyInterface.
// ...
void foo() { otherClassInstance.foo(); }
void bar() { otherClassInstance.bar(); }
void baz() { otherClassInstance.baz(); }
// ...
}
Simply deriving my class from the second class would eliminate all of this, but it doesn't make sense because the two classes are unrelated to each other (besides implementing a common interface). They represent different things - it just so happens that a lot of my class's implementation copies that of the other class. In other words, my class is implemented atop the second class, but it is not itself a subset of the second class. As we know, inheritance is meant to express an "is-a" relationship, not to share implementation, so it's inappropriate in this case.
This portion of a talk by Joshua Bloch illustrates the situation well.
I know that Java doesn't have any language support for delegation. However, is there at least some way to clean up my class's implementation so it isn't so redundant?
An answer which is not really an answer to your actual question:
I'd say, live with the boilerplate. Let IDE generate it for you. Example: in Netbeans, add the private ArrayList field, set cursor to where you'd want the methods to appear, hit alt-insert, select "Generate Delegate Method...", click the methods you want to create a delegate for in the dialog opens, submit, go through the generated methods and make them do the right thing, you're done.
It is a bit ugly, but it is still preferable to starting to mess with reflection, when you are dealing with just one class, like it sounds. Your class is probably the kind of class, which you will complete and fully test, and then hopefully never touch again. Reflection creates runtime cost which does not go away. Suffering the auto-generated boilerplate in the source file is probably preferable in this case.
First way to use http://java.sun.com/javase/6/docs/api/java/lang/reflect/Proxy.html see tutorial http://docs.oracle.com/javase/1.4.2/docs/guide/reflection/proxy.html
Second way using AOP you can create dispatcher that intercept all invocation of specific class
For both ways you need to manage methods processing using reflection API
EDITED TO SHOW IDEA
Following code taken from tutorial above just modified a little (see youListImpl.getRealArrayList() in invoke method)
public class DebugProxy implements java.lang.reflect.InvocationHandler {
private YouListImpl youListImpl;
public static Object newInstance(Object obj) {
return java.lang.reflect.Proxy.newProxyInstance(
obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(),
new DebugProxy(obj));
}
private DebugProxy(Object obj) {
this.obj = obj;
}
public Object invoke(Object proxy, Method m, Object[] args)
throws Throwable
{
Object result;
try {
System.out.println("before method " + m.getName());
result = m.invoke(youListImpl.getRealArrayList(), args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw new RuntimeException("unexpected invocation exception: " +
e.getMessage());
} finally {
System.out.println("after method " + m.getName());
}
return result;
}
}

Use of class definitions inside a method in Java

Example:
public class TestClass {
public static void main(String[] args) {
TestClass t = new TestClass();
}
private static void testMethod() {
abstract class TestMethod {
int a;
int b;
int c;
abstract void implementMe();
}
class DummyClass extends TestMethod {
void implementMe() {}
}
DummyClass dummy = new DummyClass();
}
}
I found out that the above piece of code is perfectly legal in Java. I have the following questions.
What is the use of ever having a class definition inside a method?
Will a class file be generated for DummyClass
It's hard for me to imagine this concept in an Object Oriented manner. Having a class definition inside a behavior. Probably can someone tell me with equivalent real world examples.
Abstract classes inside a method sounds a bit crazy to me. But no interfaces allowed. Is there any reason behind this?
This is called a local class.
2 is the easy one: yes, a class file will be generated.
1 and 3 are kind of the same question. You would use a local class where you never need to instantiate one or know about implementation details anywhere but in one method.
A typical use would be to create a throw-away implementation of some interface. For example you'll often see something like this:
//within some method
taskExecutor.execute( new Runnable() {
public void run() {
classWithMethodToFire.doSomething( parameter );
}
});
If you needed to create a bunch of these and do something with them, you might change this to
//within some method
class myFirstRunnableClass implements Runnable {
public void run() {
classWithMethodToFire.doSomething( parameter );
}
}
class mySecondRunnableClass implements Runnable {
public void run() {
classWithMethodToFire.doSomethingElse( parameter );
}
}
taskExecutor.execute(new myFirstRunnableClass());
taskExecutor.execute(new mySecondRunnableClass());
Regarding interfaces: I'm not sure if there's a technical issue that makes locally-defined interfaces a problem for the compiler, but even if there isn't, they wouldn't add any value. If a local class that implements a local interface were used outside the method, the interface would be meaningless. And if a local class was only going to be used inside the method, both the interface and the class would be implemented within that method, so the interface definition would be redundant.
Those are called local classes. You can find a detailed explanation and an example here. The example returns a specific implementation which we doesn't need to know about outside the method.
The class can't be seen (i.e. instantiated, its methods accessed without Reflection) from outside the method. Also, it can access the local variables defined in testMethod(), but before the class definition.
I actually thought: "No such file will be written." until I just tried it: Oh yes, such a file is created! It will be called something like A$1B.class, where A is the outer class, and B is the local class.
Especially for callback functions (event handlers in GUIs, like onClick() when a Button is clicked etc.), it's quite usual to use "anonymous classes" - first of all because you can end up with a lot of them. But sometimes anonymous classes aren't good enough - especially, you can't define a constructor on them. In these cases, these method local classes can be a good alternative.
The real purpose of this is to allow us to create classes inline in function calls to console those of us who like to pretend that we're writing in a functional language ;)
The only case when you would like to have a full blown function inner class vs anonymous class ( a.k.a. Java closure ) is when the following conditions are met
you need to supply an interface or abstract class implementation
you want to use some final parameters defined in calling function
you need to record some state of execution of the interface call.
E.g. somebody wants a Runnable and you want to record when the execution has started and ended.
With anonymous class it is not possible to do, with inner class you can do this.
Here is an example do demonstrate my point
private static void testMethod (
final Object param1,
final Object param2
)
{
class RunnableWithStartAndEnd extends Runnable{
Date start;
Date end;
public void run () {
start = new Date( );
try
{
evalParam1( param1 );
evalParam2( param2 );
...
}
finally
{
end = new Date( );
}
}
}
final RunnableWithStartAndEnd runnable = new RunnableWithStartAndEnd( );
final Thread thread = new Thread( runnable );
thread.start( );
thread.join( );
System.out.println( runnable.start );
System.out.println( runnable.end );
}
Before using this pattern though, please evaluate if plain old top-level class, or inner class, or static inner class are better alternatives.
The main reason to define inner classes (within a method or a class) is to deal with accessibility of members and variables of the enclosing class and method.
An inner class can look up private data members and operate on them. If within a method it can deal with final local variable as well.
Having inner classes does help in making sure this class is not accessible to outside world. This holds true especially for cases of UI programming in GWT or GXT etc where JS generating code is written in java and behavior for each button or event has to be defined by creating anonymous classes
I've came across a good example in the Spring. The framework is using concept of local class definitions inside of the method to deal with various database operations in a uniform way.
Assume you have a code like this:
JdbcTemplate jdbcOperations = new JdbcTemplate(this.myDataSource);
jdbcOperations.execute("call my_stored_procedure()")
jdbcOperations.query(queryToRun, new MyCustomRowMapper(), withInputParams);
jdbcOperations.update(queryToRun, withInputParams);
Let's first look at the implementation of the execute():
#Override
public void execute(final String sql) throws DataAccessException {
if (logger.isDebugEnabled()) {
logger.debug("Executing SQL statement [" + sql + "]");
}
/**
* Callback to execute the statement.
(can access method local state like sql input parameter)
*/
class ExecuteStatementCallback implements StatementCallback<Object>, SqlProvider {
#Override
#Nullable
public Object doInStatement(Statement stmt) throws SQLException {
stmt.execute(sql);
return null;
}
#Override
public String getSql() {
return sql;
}
}
//transforms method input into a functional Object
execute(new ExecuteStatementCallback());
}
Please note the last line. Spring does this exact "trick" for the rest of the methods as well:
//uses local class QueryStatementCallback implements StatementCallback<T>, SqlProvider
jdbcOperations.query(...)
//uses local class UpdateStatementCallback implements StatementCallback<Integer>, SqlProvider
jdbcOperations.update(...)
The "trick" with local classes allows the framework to deal with all of those scenarios in a single method which accept those classes via StatementCallback interface.
This single method acts as a bridge between actions (execute, update) and common operations around them (e.g execution, connection management, error translation and dbms console output)
public <T> T execute(StatementCallback<T> action) throws DataAccessException {
Assert.notNull(action, "Callback object must not be null");
Connection con = DataSourceUtils.getConnection(obtainDataSource());
Statement stmt = null;
try {
stmt = con.createStatement();
applyStatementSettings(stmt);
//
T result = action.doInStatement(stmt);
handleWarnings(stmt);
return result;
}
catch (SQLException ex) {
// Release Connection early, to avoid potential connection pool deadlock
// in the case when the exception translator hasn't been initialized yet.
String sql = getSql(action);
JdbcUtils.closeStatement(stmt);
stmt = null;
DataSourceUtils.releaseConnection(con, getDataSource());
con = null;
throw translateException("StatementCallback", sql, ex);
}
finally {
JdbcUtils.closeStatement(stmt);
DataSourceUtils.releaseConnection(con, getDataSource());
}
}
Everything is clear here but I wanted to place another example of reasonable use case for this definition type of class for the next readers.
Regarding #jacob-mattison 's answer, If we assume we have some common actions in these throw-away implementations of the interface, So, it's better to write it once but keep the implementations anonymous too:
//within some method
abstract class myRunnableClass implements Runnable {
protected abstract void DO_AN_SPECIFIC_JOB();
public void run() {
someCommonCode();
//...
DO_AN_SPECIFIC_JOB();
//..
anotherCommonCode();
}
}
Then it's easy to use this defined class and just implement the specific task separately:
taskExecutor.execute(new myRunnableClass() {
protected void DO_AN_SPECIFIC_JOB() {
// Do something
}
});
taskExecutor.execute(new myRunnableClass() {
protected void DO_AN_SPECIFIC_JOB() {
// Do another thing
}
});

Why can't I use a try block around my super() call?

So, in Java, the first line of your constructor HAS to be a call to super... be it implicitly calling super(), or explicitly calling another constructor. What I want to know is, why can't I put a try block around that?
My specific case is that I have a mock class for a test. There is no default constructor, but I want one to make the tests simpler to read. I also want to wrap the exceptions thrown from the constructor into a RuntimeException.
So, what I want to do is effectively this:
public class MyClassMock extends MyClass {
public MyClassMock() {
try {
super(0);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// Mocked methods
}
But Java complains that super isn't the first statement.
My workaround:
public class MyClassMock extends MyClass {
public static MyClassMock construct() {
try {
return new MyClassMock();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public MyClassMock() throws Exception {
super(0);
}
// Mocked methods
}
Is this the best workaround? Why doesn't Java let me do the former?
My best guess as to the "why" is that Java doesn't want to let me have a constructed object in a potentially inconsistent state... however, in doing a mock, I don't care about that. It seems I should be able to do the above... or at least I know that the above is safe for my case... or seems as though it should be anyways.
I am overriding any methods I use from the tested class, so there is no risk that I am using uninitialized variables.
Unfortunately, compilers can't work on theoretical principles, and even though you may know that it is safe in your case, if they allowed it, it would have to be safe for all cases.
In other words, the compiler isn't stopping just you, it's stopping everyone, including all those that don't know that it is unsafe and needs special handling. There are probably other reasons for this as well, as all languages usually have ways to do unsafe things if one knows how to deal with them.
In C# .NET there are similar provisions, and the only way to declare a constructor that calls a base constructor is this:
public ClassName(...) : base(...)
in doing so, the base constructor will be called before the body of the constructor, and you cannot change this order.
It's done to prevent someone from creating a new SecurityManager object from untrusted code.
public class Evil : SecurityManager {
Evil()
{
try {
super();
} catch { Throwable t }
{
}
}
}
I know this is an old question, but I liked it, and as such, I decided to give it an answer of my own. Perhaps my understanding of why this cannot be done will contribute to the discussion and to future readers of your interesting question.
Let me start with an example of failing object construction.
Let's define a class A, such that:
class A {
private String a = "A";
public A() throws Exception {
throw new Exception();
}
}
Now, let's assume we would like to create an object of type A in a try...catch block.
A a = null;
try{
a = new A();
}catch(Exception e) {
//...
}
System.out.println(a);
Evidently, the output of this code will be: null.
Why Java does not return a partially constructed version of A? After all, by the point the constructor fails, the object's name field has already been initialized, right?
Well, Java can't return a partially constructed version of A because the object was not successfully built. The object is in a inconsistent state, and it is therefore discarded by Java. Your variable A is not even initialized, it is kept as null.
Now, as you know, to fully build a new object, all its super classes must be initialized first. If one of the super classes failed to execute, what would be the final state of the object? It is impossible to determine that.
Look at this more elaborate example
class A {
private final int a;
public A() throws Exception {
a = 10;
}
}
class B extends A {
private final int b;
public B() throws Exception {
methodThatThrowsException();
b = 20;
}
}
class C extends B {
public C() throws Exception { super(); }
}
When the constructor of C is invoked, if an exception occurs while initializing B, what would be the value of the final int variable b?
As such, the object C cannot be created, it is bogus, it is trash, it is not fully initialized.
For me, this explains why your code is illegal.
I can't presume to have a deep understanding of Java internals, but it is my understanding that, when a compiler needs to instantiate a derived class, it has to first create the base (and its base before that(...)) and then slap on the extensions made in the subclass.
So it is not even the danger of uninited variables or anything like that at all. When you try to do something in the subclass' constructor before the base class' constructor, you are basically asking the compiler to extend a base object instance that doesn't exist yet.
Edit:In your case, MyClass becomes the base object, and MyClassMock is a subclass.
I don't know how Java is implemented internally, but if the constructor of the superclass throws an exception, then there isn't a instance of the class you extend. It would be impossible to call the toString() or equals() methods, for example, since they are inherited in most cases.
Java may allow a try/catch around the super() call in the constructor if 1. you override ALL methods from the superclasses, and 2. you don't use the super.XXX() clause, but that all sounds too complicated to me.
I know this question has numerous answers, but I'd like to give my little tidbit on why this wouldn't be allowed, specifically to answer why Java does not allow you to do this. So here you go...
Now, keep in mind that super() has to be called before anything else in a subclass's constructor, so, if you did use try and catch blocks around your super() call, the blocks would have to look like this:
try {
super();
...
} catch (Exception e) {
super(); //This line will throw the same error...
...
}
If super() fails in the try block, it HAS to be executed first in the catch block, so that super runs before anything in your subclass`s constructor. This leaves you with the same problem you had at the beginning: if an exception is thrown, it isn't caught. (In this case it just gets thrown again in the catch block.)
Now, the above code is in no way allowed by Java either. This code may execute half of the first super call, and then call it again, which could cause some problems with some super classes.
Now, the reason that Java doesn't let you throw an exception instead of calling super() is because the exception could be caught somewhere else, and the program would continue without calling super() on your subclass object, and possibly because the exception could take your object as a parameter and try to change the value of inherited instance variables, which would not yet have been initialized.
One way to get around it is by calling a private static function. The try-catch can then be placed in the function body.
public class Test {
public Test() {
this(Test.getObjectThatMightThrowException());
}
public Test(Object o) {
//...
}
private static final Object getObjectThatMightThrowException() {
try {
return new ObjectThatMightThrowAnException();
} catch(RuntimeException rtx) {
throw new RuntimeException("It threw an exception!!!", rtx);
}
}
}

Categories