What are all the different ways to create an objec

2018-12-31 19:51发布

Had a conversation with a coworker the other day about this.

There's the obvious which is to use a constructor, but what other ways are there?

标签: java
22条回答
闭嘴吧你
2楼-- · 2018-12-31 20:17

We can also create the object in this way:-

String s ="Hello";

Nobody has discuss it.

查看更多
弹指情弦暗扣
3楼-- · 2018-12-31 20:19

Also, you can de-serialize data into an object. This doesn't go through the class Constructor !


UPDATED : Thanks Tom for pointing that out in your comment ! And Michael also experimented.

It goes through the constructor of the most derived non-serializable superclass.
And when that class has no no-args constructor, a InvalidClassException is thrown upon de-serialization.

Please see Tom's answer for a complete treatment of all cases ;-)
is there any other way of creating an object without using "new" keyword in java

查看更多
时光乱了年华
4楼-- · 2018-12-31 20:20

There are various ways:

  • Through Class.newInstance.
  • Through Constructor.newInstance.
  • Through deserialisation (uses the no-args constructor of the most derived non-serialisable base class).
  • Through Object.clone (does not call a constructor).
  • Through JNI (should call a constructor).
  • Through any other method that calls a new for you.
  • I guess you could describe class loading as creating new objects (such as interned Strings).
  • A literal array as part of the initialisation in a declaration (no constructor for arrays).
  • The array in a "varargs" (...) method call (no constructor for arrays).
  • Non-compile time constant string concatenation (happens to produce at least four objects, on a typical implementation).
  • Causing an exception to be created and thrown by the runtime. For instance throw null; or "".toCharArray()[0].
  • Oh, and boxing of primitives (unless cached), of course.
  • JDK8 should have lambdas (essentially concise anonymous inner classes), which are implicitly converted to objects.
  • For completeness (and Paŭlo Ebermann), there's some syntax with the new keyword as well.
查看更多
余生无你
5楼-- · 2018-12-31 20:20

there is also ClassLoader.loadClass(string) but this is not often used.

and if you want to be a total lawyer about it, arrays are technically objects because of an array's .length property. so initializing an array creates an object.

查看更多
登录 后发表回答