我是一名Java开发人员.在一次采访中,我被问到一个关于私人建筑师的问题:
你可以访问类的私有构造函数并实例化它吗?
我回答'不',但错了.
你能解释为什么我错了,举一个用私有构造函数实例化对象的例子吗?
今天在我的采访中,一位采访者让我写了一个Singleton课程.我给出了答案
public class Singleton {
private static Singleton ref;
private Singleton() {
}
public static Singleton getInstance() {
if (ref == null) {
ref = new Singleton();
}
return ref;
}
}
Run Code Online (Sandbox Code Playgroud)
突然他告诉我这是写作课的老方法.任何人都可以帮助我,为什么他这样说.
我有以下代码:
public void myMethod(Object... args) {
System.out.println("this is myMethod");
}
public void invokeMyMethod() {
Method s = this.getClass().getMethod("myMethod", Object[].class);
Object[] ex = new Object[2];
ex[0] = "hi";
ex[1] = "there";
s.invoke(this, ex);
}
Run Code Online (Sandbox Code Playgroud)
我得到异常java.lang.IllegalArgumentException:错误的参数数量.怎么了?
我不太确定如何反映一个只有包级访问权限的类。我知道如何反映任何具有公共访问权限的类,但我无法弄清楚如何反映以下示例:
public class Main {
public static void main(String[] args) {
test t = new test();
Constructor<one.oneimpl> con = one.oneimpl.class.getDeclaredConstructor(test.class);
oneimpl o = con.newInstance(t);
o.doIt();
}
}
Run Code Online (Sandbox Code Playgroud)
======================
package one;
// implementation class for mimicking android api
class oneimpl extends one {
Test mTest;
private oneimpl(test t){mTest = t;}
public void doIt(){System.out.println("Do It!");}
public void dontDoit(){System.out.println("Don't Do It!");}
}
Run Code Online (Sandbox Code Playgroud)
======================
package one;
// abstract class for mimicking android api
abstract class one {
public void doIt();
public void dontDoIt();
} …Run Code Online (Sandbox Code Playgroud) 谁能告诉我我在做错了什么?
private static java.lang.Math a = new java.lang.Math();
Run Code Online (Sandbox Code Playgroud)
这导致了错误,但我不知道为什么.