An interview question about Java reflection.

huangapple go评论72阅读模式
英文:

An interview question about Java reflection

问题

public class Test {
    public static void main(String[] arges) throws Exception {
        IA ia = (IA) createObject(IA.class.getName() + "$getName=Abc");
        System.out.println(ia.getName()); //output: Abc
        ia = (IA) createObject(IA.class.getName() + "$getName=Bcd");
        System.out.println(ia.getName()); //output: Bcd
    }

    public static Object createObject(String str) throws Exception {
        String[] parts = str.split("\$");
        String className = parts[0];
        String[] methodParts = parts[1].split("=");
        String methodName = methodParts[0];
        String returnValue = methodParts[1];

        Class<?> clazz = Class.forName(className);
        IA proxy = (IA) java.lang.reflect.Proxy.newProxyInstance(
                clazz.getClassLoader(),
                new Class[]{IA.class},
                (proxyObj, method, args) -> returnValue
        );
        return proxy;
    }

    interface IA {
        String getName();
    }
}
英文:
public class Test {
    // 修改方法createObject内容,实现main里面的两处打印 
    public static void main(String[] arges) throws Exception {  
        IA ia = (IA) createObject(IA.class.getName() + &quot;$getName =Abc&quot;);
        System.out.println(ia.getName()); //output: Abc
        ia = (IA) createObject(IA.class.getName() + &quot;$getName= Bcd&quot;);
        System.out.println(ia.getName()); //output: Bcd
    }

    // please coding in createObject for true output
    public static Object createObject(String str) throws Exception {
        // your coding
    }

    interface IA {
        String getName();
    }

}

Through Google, I learned about coding through the use of reflection and dynamic proxies. But when I tried coding, I found that I couldn't do it...

An interview question about Java reflection.

答案1

得分: 0

Sure, here's the translated code:

public class Test {
    public static void main(String[] args) throws Exception {
        IA ia = (IA) createObject(IA.class.getName() + "$getName =Abc");
        System.out.println(ia.getName()); //output: Abc
        ia = (IA) createObject(IA.class.getName() + "$getName= Bcd");
        System.out.println(ia.getName()); //output: Bcd
    }

    // please code in createObject for true output
    public static Object createObject(String str) throws Exception {
        String[] split = str.split("\$getName\\s?=\\s?");
        String classname = split[0];
        String value = split[1];
        return Proxy.newProxyInstance(
            Class.forName(classname).getClassLoader(),
            new Class[] { IA.class },
            (proxy, method, args) -> {
                if ("getName".equals(method.getName()))
                    return value;
                throw new Exception();
            });
    }

    interface IA {
        String getName();
    }
}

Outputs:

Abc
Bcd
英文:

What about this?

public class Test {
	public static void main(String[] arges) throws Exception {
		IA ia = (IA) createObject(IA.class.getName() + &quot;$getName =Abc&quot;);
		System.out.println(ia.getName()); //output: Abc
		ia = (IA) createObject(IA.class.getName() + &quot;$getName= Bcd&quot;);
		System.out.println(ia.getName()); //output: Bcd
	}

	// please coding in createObject for true output
	public static Object createObject(String str) throws Exception {
		String[] split = str.split(&quot;\$getName\\s?=\\s?&quot;);
		String classname = split[0];
		String value = split[1];
		return Proxy.newProxyInstance(Class.forName(classname).getClassLoader(), new Class[] { IA.class },
				(proxy, method, args) -&gt; {
					if (&quot;getName&quot;.equals(method.getName()))
						return value;
					throw new Exception();
				});
	}

	interface IA {
		String getName();
	}
}

Outputs:

Abc
Bcd

答案2

得分: 0

Sure, here's the translated code:

public static Object createObject(String str) throws Exception {
    String value = str.split("=")[1].trim();
    return (IA) () -> value;
}

Reflection isn't necessary since we're only interested in the part after the equal sign.

英文:

I would do it like this:

public static Object createObject(String str) throws Exception {
      String value = str.split(&quot;=&quot;)[1].trim();
      return (IA) () -&gt; value;
    }

There is not really reflection needed because we only care about the part after the equation mark.

答案3

得分: 0

Here's the translation of the code you provided:

public static Object createObject(String str) throws Exception {
    final String className = str.substring(0, str.lastIndexOf("$"));
    final String methodName = str.substring(str.lastIndexOf("$") + 1, str.indexOf("=")).trim();
    final String value = str.substring(str.indexOf("=") + 1).trim();
    return Proxy.newProxyInstance(
        Class.forName(className).getClassLoader(),
        new Class[] { Class.forName(className) },
        (proxy, method, methodArgs) -> {
            if (method.getName().equals(methodName)) {
                return value;
            } else {
                throw new UnsupportedOperationException("Unsupported method: " + method.getName());
            }
        }
    );
}
英文:

As the class name and method name are provided in the parameter, I made no assumption on the IA interface. Everything is dynamic.

// please coding in createObject for true output
public static Object createObject(String str) throws Exception {
	final String className = str.substring(0, str.lastIndexOf(&quot;$&quot;));
	final String methodName=str.substring(str.lastIndexOf(&quot;$&quot;)+1,str.indexOf(&quot;=&quot;)).trim();
	final String value = str.substring(str.indexOf(&quot;=&quot;) + 1).trim();
	return Proxy.newProxyInstance(Class.forName(className).getClassLoader(), new Class[] { Class.forName(className) },
			(proxy, method, methodArgs) -&gt; {
				if (method.getName().equals(methodName)) {
					return value;
				} else {
					throw new UnsupportedOperationException(&quot;Unsupported method: &quot; + method.getName());
				}
			});
}

huangapple
  • 本文由 发表于 2020年8月14日 20:27:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/63412760.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定