Im very new to programming and want to know if I can somehow get the object from a class where I already used new MyClass();
to use it in another class and that I don't need to use new MyClass();
again. Hope you get the point.
我是一个非常新的编程,想要知道我是否能以某种方式从我已经使用过新MyClass()的类中获取对象;在另一个类中使用它,我不需要使用新的MyClass();再次。希望你明白这一点。
Some very simple example:
一些非常简单的例子:
class MyFirstClass
{
Something st = new Something();
}
class Something()
{
// some code
}
class MySecondClass
{
// This is where I want to use the object from class Something()
// like
getObjectFromClass()
}
6 个解决方案
#1
2
You can use Singleton pattern to achieve this
您可以使用Singleton模式来实现此目的
This is kickoff example of such object. It has a private constructor and public class method getInstance
:
这是这种对象的启动示例。它有一个私有构造函数和公共类方法getInstance:
static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class
静态方法,在其声明中具有静态修饰符,应该使用类名调用,而不需要创建类的实例
When we make a call to getInstance
it checks if an object has been created already and will return an instance of already created objected, if it wasn't created it will create a new object and return it.
当我们调用getInstance时,它会检查是否已经创建了一个对象,并且将返回已经创建的对象的实例,如果它没有被创建,它将创建一个新对象并返回它。
public class SingletonObject {
private static int instantiationCounter = 0; //we use this class variable to count how many times this object was instantiated
private static volatile SingletonObject instance;
private SingletonObject() {
instantiationCounter++;
}
public static SingletonObject getInstance() {
if (instance == null ) {
instance = new SingletonObject();
}
return instance;
}
public int getInstantiationCounter(){
return instantiationCounter;
}
}
To check how does this work you can use the following code:
要检查这是如何工作的,您可以使用以下代码:
public static void main(String[] args) {
SingletonObject object = SingletonObject.getInstance();
System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");
object = SingletonObject.getInstance();
System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");
object = SingletonObject.getInstance();
System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");
}
#2
3
Since you have just started coding won't give you a term like reflection and all.. here is one of the simple way is have a public getter()
method.
既然你刚开始编码就不会给你一个像反射这样的术语..这里有一个简单的方法就是有一个公共的getter()方法。
Consider this simple example
考虑这个简单的例子
class Something {
private int a=10;
public int getA() {
return a;
}
}
Here is the First which has a public method which return the object that i created in this class for the Something Class
这是第一个有一个公共方法,它返回我在这个类中为Something类创建的对象
class MyFirstClass {
private Something st;
public MyFirstClass() {
this.st = new Something();
}
public Something getSt() {
return st;
}
}
Accessing it from another Class
从另一个类访问它
class MySecondClass {
public static void main(String...strings ){
MyFirstClass my =new MyFirstClass();
System.out.println(my.getSt().getA());
}
}
Output: 10
If You wan't to verify
如果你不想验证
Inject this function in MyFirstClass
在MyFirstClass中注入此函数
public void printHashcode(){
System.out.println(st);
}
and then print the hash codes from both methods in MySecondClass
然后从MySecondClass中的两个方法打印哈希码
class MySecondClass {
class MySecondClass {
public static void main(String...strings ){
MyFirstClass my =new MyFirstClass();
System.out.println(my.getSt());
my.printHashcode();
}
}
You will see that indeed you are using the Object created in MyFirstClass
in MySecondClass
.
您将看到确实在MySecondClass中使用MyFirstClass中创建的Object。
Because this will give you same hashcode output.
因为这会给你相同的哈希码输出。
Output On my machine.
输出在我的机器上。
Something@2677622b
Something@2677622b
#3
1
Singleton pattern lets you have single instance which is 'globally' accessible by other classes. This pattern will 'guarantee' that you have only one instance in memory. There are exceptions to one instance benefit, such as when deserializaing from file unless care is taken and readResolve
is implemented.
单例模式允许您拥有其他类可“全局”访问的单个实例。此模式将“保证”您在内存中只有一个实例。一个实例的好处有例外,例如从文件反序列化时除非小心并且实现了readResolve。
Note that class Something right now has no state(fields), only behavior so it is safe to share between multiple threads. If Something had state, you would need to provide some kind of synchronization mechanism in multi thread environment.
请注意,类Something现在没有状态(字段),只有行为,所以在多个线程之间共享是安全的。如果Something有状态,则需要在多线程环境中提供某种同步机制。
Given such stateless Singleton, it would be better to replace it with class that contains only static methods. That is, unless you are implementing pattern such as Strategy which requires interface implementation, then it would be good idea to cache instance like bellow with Singleton pattern.
鉴于这样的无状态Singleton,最好用仅包含静态方法的类替换它。也就是说,除非你正在实现需要接口实现的策略之类的策略,否则最好像使用Singleton模式一样缓存实例。
You should rework your Something class like this to achieve singleton:
你应该像这样重做你的Something类来实现单例:
public class Something {
private static final Something INSTANCE = new Something ();
private Something () {
// exists to defeat instantiation
}
public Something getInstance() {
return INSTANCE;
}
public void service() {
//...
}
public void anotherService() {
//..
}
}
#4
1
Instead of using the Singleton pattern, a better pattern to use is dependency injection. Essentially, you instantiate the class you want to share, and pass it in the constructor of every class that needs it.
而不是使用Singleton模式,更好的模式是依赖注入。实质上,您实例化要共享的类,并将其传递给需要它的每个类的构造函数。
public class MainClass {
public static void main(String[] args) {
SharedClass sharedClass = new SharedClass();
ClassA classA = new ClassA(sharedClass);
ClassB classB = new ClassB(sharedClass);
}
}
public class ClassA {
private SharedClass sharedClass;
public ClassA(SharedClass sharedClass) {
this.sharedClass = sharedClass;
}
}
public class ClassB {
private SharedClass sharedClass;
public ClassB(SharedClass sharedClass) {
this.sharedClass = sharedClass;
}
}
#5
1
If FirstClass and SecondClass are somehow related, you can extract that common object you're using to a super class, and that's the only scope in which you're planning to use this object.
如果FirstClass和SecondClass以某种方式相关,您可以将您正在使用的公共对象提取到超类,这是您计划使用此对象的唯一范围。
public class SuperClass{
Something st = new Something();
public Something getObjectFromClass(){
return st;
}
}
public class MyFirstClass extends SuperClass{
getObjectFromClass();
}
public class MySecondClass extends SuperClass{
getObjectFromClass();
}
Otherwise, if you plan to use that instance somewhere else you should use a Singleton object. The easiest way of doing this is:
否则,如果您计划在其他地方使用该实例,则应使用Singleton对象。最简单的方法是:
enum Singleton
{
INSTANCE;
private final Something obj;
Singleton()
{
obj = new Something();
}
public Something getObject()
{
return obj;
}
}
You use it:
你用吧:
Singleton.INSTANCE.getObject();
#6
1
Okay firstly you can use inheritance e.g.
好的,首先你可以使用继承,例如
class MyFirstClass
{
Something st = new Something();
}
class Something()
{
// some code
}
class MySecondClass extends myFirstClass
{
// This is where I want to use the object from class Something()
// like
MySecondClass obj = new MySecondClass();
obj.method(); //Method from myfirstclass accessible from second class object
}
Or if you dont want any objects and just the method you can implement interfaces e.g.
或者,如果您不想要任何对象,只需要方法即可实现接口,例如
public interface MyFirstClass
{
//example method
public abstract void saying(); //no body required
Something st = new Something();
}
class Something()
{
// some code
}
class MySecondClass implements MyFirstClass //Have to implement methods
{
public void saying(){ //Method implemented from firstClass no obj
System.out.println("Hello World");
}
getObjectFromClass()
}
#1
2
You can use Singleton pattern to achieve this
您可以使用Singleton模式来实现此目的
This is kickoff example of such object. It has a private constructor and public class method getInstance
:
这是这种对象的启动示例。它有一个私有构造函数和公共类方法getInstance:
static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class
静态方法,在其声明中具有静态修饰符,应该使用类名调用,而不需要创建类的实例
When we make a call to getInstance
it checks if an object has been created already and will return an instance of already created objected, if it wasn't created it will create a new object and return it.
当我们调用getInstance时,它会检查是否已经创建了一个对象,并且将返回已经创建的对象的实例,如果它没有被创建,它将创建一个新对象并返回它。
public class SingletonObject {
private static int instantiationCounter = 0; //we use this class variable to count how many times this object was instantiated
private static volatile SingletonObject instance;
private SingletonObject() {
instantiationCounter++;
}
public static SingletonObject getInstance() {
if (instance == null ) {
instance = new SingletonObject();
}
return instance;
}
public int getInstantiationCounter(){
return instantiationCounter;
}
}
To check how does this work you can use the following code:
要检查这是如何工作的,您可以使用以下代码:
public static void main(String[] args) {
SingletonObject object = SingletonObject.getInstance();
System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");
object = SingletonObject.getInstance();
System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");
object = SingletonObject.getInstance();
System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");
}
#2
3
Since you have just started coding won't give you a term like reflection and all.. here is one of the simple way is have a public getter()
method.
既然你刚开始编码就不会给你一个像反射这样的术语..这里有一个简单的方法就是有一个公共的getter()方法。
Consider this simple example
考虑这个简单的例子
class Something {
private int a=10;
public int getA() {
return a;
}
}
Here is the First which has a public method which return the object that i created in this class for the Something Class
这是第一个有一个公共方法,它返回我在这个类中为Something类创建的对象
class MyFirstClass {
private Something st;
public MyFirstClass() {
this.st = new Something();
}
public Something getSt() {
return st;
}
}
Accessing it from another Class
从另一个类访问它
class MySecondClass {
public static void main(String...strings ){
MyFirstClass my =new MyFirstClass();
System.out.println(my.getSt().getA());
}
}
Output: 10
If You wan't to verify
如果你不想验证
Inject this function in MyFirstClass
在MyFirstClass中注入此函数
public void printHashcode(){
System.out.println(st);
}
and then print the hash codes from both methods in MySecondClass
然后从MySecondClass中的两个方法打印哈希码
class MySecondClass {
class MySecondClass {
public static void main(String...strings ){
MyFirstClass my =new MyFirstClass();
System.out.println(my.getSt());
my.printHashcode();
}
}
You will see that indeed you are using the Object created in MyFirstClass
in MySecondClass
.
您将看到确实在MySecondClass中使用MyFirstClass中创建的Object。
Because this will give you same hashcode output.
因为这会给你相同的哈希码输出。
Output On my machine.
输出在我的机器上。
Something@2677622b
Something@2677622b
#3
1
Singleton pattern lets you have single instance which is 'globally' accessible by other classes. This pattern will 'guarantee' that you have only one instance in memory. There are exceptions to one instance benefit, such as when deserializaing from file unless care is taken and readResolve
is implemented.
单例模式允许您拥有其他类可“全局”访问的单个实例。此模式将“保证”您在内存中只有一个实例。一个实例的好处有例外,例如从文件反序列化时除非小心并且实现了readResolve。
Note that class Something right now has no state(fields), only behavior so it is safe to share between multiple threads. If Something had state, you would need to provide some kind of synchronization mechanism in multi thread environment.
请注意,类Something现在没有状态(字段),只有行为,所以在多个线程之间共享是安全的。如果Something有状态,则需要在多线程环境中提供某种同步机制。
Given such stateless Singleton, it would be better to replace it with class that contains only static methods. That is, unless you are implementing pattern such as Strategy which requires interface implementation, then it would be good idea to cache instance like bellow with Singleton pattern.
鉴于这样的无状态Singleton,最好用仅包含静态方法的类替换它。也就是说,除非你正在实现需要接口实现的策略之类的策略,否则最好像使用Singleton模式一样缓存实例。
You should rework your Something class like this to achieve singleton:
你应该像这样重做你的Something类来实现单例:
public class Something {
private static final Something INSTANCE = new Something ();
private Something () {
// exists to defeat instantiation
}
public Something getInstance() {
return INSTANCE;
}
public void service() {
//...
}
public void anotherService() {
//..
}
}
#4
1
Instead of using the Singleton pattern, a better pattern to use is dependency injection. Essentially, you instantiate the class you want to share, and pass it in the constructor of every class that needs it.
而不是使用Singleton模式,更好的模式是依赖注入。实质上,您实例化要共享的类,并将其传递给需要它的每个类的构造函数。
public class MainClass {
public static void main(String[] args) {
SharedClass sharedClass = new SharedClass();
ClassA classA = new ClassA(sharedClass);
ClassB classB = new ClassB(sharedClass);
}
}
public class ClassA {
private SharedClass sharedClass;
public ClassA(SharedClass sharedClass) {
this.sharedClass = sharedClass;
}
}
public class ClassB {
private SharedClass sharedClass;
public ClassB(SharedClass sharedClass) {
this.sharedClass = sharedClass;
}
}
#5
1
If FirstClass and SecondClass are somehow related, you can extract that common object you're using to a super class, and that's the only scope in which you're planning to use this object.
如果FirstClass和SecondClass以某种方式相关,您可以将您正在使用的公共对象提取到超类,这是您计划使用此对象的唯一范围。
public class SuperClass{
Something st = new Something();
public Something getObjectFromClass(){
return st;
}
}
public class MyFirstClass extends SuperClass{
getObjectFromClass();
}
public class MySecondClass extends SuperClass{
getObjectFromClass();
}
Otherwise, if you plan to use that instance somewhere else you should use a Singleton object. The easiest way of doing this is:
否则,如果您计划在其他地方使用该实例,则应使用Singleton对象。最简单的方法是:
enum Singleton
{
INSTANCE;
private final Something obj;
Singleton()
{
obj = new Something();
}
public Something getObject()
{
return obj;
}
}
You use it:
你用吧:
Singleton.INSTANCE.getObject();
#6
1
Okay firstly you can use inheritance e.g.
好的,首先你可以使用继承,例如
class MyFirstClass
{
Something st = new Something();
}
class Something()
{
// some code
}
class MySecondClass extends myFirstClass
{
// This is where I want to use the object from class Something()
// like
MySecondClass obj = new MySecondClass();
obj.method(); //Method from myfirstclass accessible from second class object
}
Or if you dont want any objects and just the method you can implement interfaces e.g.
或者,如果您不想要任何对象,只需要方法即可实现接口,例如
public interface MyFirstClass
{
//example method
public abstract void saying(); //no body required
Something st = new Something();
}
class Something()
{
// some code
}
class MySecondClass implements MyFirstClass //Have to implement methods
{
public void saying(){ //Method implemented from firstClass no obj
System.out.println("Hello World");
}
getObjectFromClass()
}