会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132463个问题
Python 全系列/第七阶段:网页编程基础/CSS 样式 16111楼
JAVA 全系列/第十一阶段:智能家居项目(旧)/至尊智能家居第二天 16112楼

老师,使用 new 关键字新建 Student 类的对象 student,和获取 Class 对象,然后调用 newInstance() 方法新建对象 students 有啥区别?应该都算是调用 Student 类的无参构造器新建对象吧。

public class ReflectionPerformanceTest01 {

    public static void main(String[] args) throws Exception {
        // Reflection
        // obtain Class object
        Student student = new Student();
        Class classObject01 = student.getClass();

        Class classObject02 = Student.class;

        Class classObject03 = Class.forName("com.bjsxt.demo.Student");

        // test students is equal student?是不是都是算是调用无参构造器创建对象?
        // 此外,使用这两种方式创建的对象调用方法,很明显一个使用了反射,一个没有使用反射,所以效率会有明显的差距。
        Student students =(Student) classObject03.newInstance();

        long reflectionStart = System.currentTimeMillis();
        Method method = classObject03.getMethod("setName", String.class);

        final int cycle = 10000000;
        for ( int i = 0; i < cycle; ++i) {
            // method.invoke(student,"John");   // new 关键字新建对象 student
            method.invoke(students,"John");   // Class 对象调用 newInstance() 方法获取对象
        }
        long reflectionEnd = System.currentTimeMillis();
        System.out.println(reflectionEnd - reflectionStart);
        System.out.println("----------------");

        // non reflection
        long start = System.currentTimeMillis();
        for (int i = 0; i < cycle; ++i) {
            student.setName("Marry");
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }
}


JAVA 全系列/第二阶段:JAVA 基础深化和提高/反射技术(旧) 16113楼
JAVA 全系列/第十一阶段:分布式RPC调用和分布式文件存储/Dubbo 16114楼
Python 全系列/第十三阶段:高并发性能怪兽-Tornado 框架/Tornado 深入学习(旧) 16115楼

老师,在29-34行中,使用接口Animal类来获取Mouse,Bird的run,fly获取不了,视频里老师也没有进行这2个参数的演示。

from flask import Flask
from flask_graphql import GraphQLView
import graphene

class Animal(graphene.Interface):  #定义一个接口类
    id=graphene.ID()
    name=graphene.String()

class Mouse(graphene.ObjectType):
    class Meta:
        interfaces=(Animal,)    #继承接口中的属性
    run = graphene.String()     #自定义属性

class Bird(graphene.ObjectType):
    class Meta:
        interfaces = (Animal,)  #继承接口中的属性
    fly = graphene.String()     #自定义属性

class Query(graphene.ObjectType):
    mouse=graphene.Field(Mouse) #获得Mouse属性
    bird=graphene.Field(Bird)   #获得Bird属性
    animal=graphene.Field(Animal,type_=graphene.Int(required = True))

    def resolve_mouse(self,info):
        return Mouse(id=1,name='杰瑞',run='汤姆快跑呀~~')
    def resolve_bird(self,info):
        return Bird(id=2,name='高书博',fly='汤姆快跑呀~~')
    # def resolve_animal(self,info,type_):
    #     if type_==1:
    #         return Mouse(id=3, name='狗蛋高书博', run='追唐老鸭啦~~~')
    #     elif type_==2:
    #         return Bird(id=4, name='狗子高书博', fly='跑呀~Tom来了!!')

    def resolve_animal(self,info,type_):
        # return Animal(id=3,name='动物') #  "message": "An Interface cannot be intitialized",
        if type_ == 1:
            return Mouse(id= 4, name='米老鼠',run='追唐老鸭啦~~~')
        else:
            return Bird(id = 3,name='鹦鹉',fly = '跑呀~Tom来了!!')

if __name__=='__main__':
    schema=graphene.Schema(query=Query)  #查询Query
    app=Flask(__name__) #创建flask对象
    # /graphql:视图的URL, GraphQLView.as_view:将映射函数转换成视图函数 ,'grapql':视图名称  ,
    # 把schema注册到schema方法里, graphiql=True:开启插件应用
    app.add_url_rule('/graphql', view_func=GraphQLView.as_view('grapql', schema=schema, graphiql=True))
    app.run()

image.png

Python 全系列/第八阶段:轻量级Web开发利器-Flask框架/GraphQL 16117楼

User 类:

public class User {

    private String userName;
    private int userAge;
    public String location;

    public User() {
    }

    public User(String userName, int userAge, String location) {
        this.userName = userName;
        this.userAge = userAge;
        this.location = location;
    }

    // private modifier
    private User(int userAge) {
        this.userAge = userAge;
    }

     /*only the name is different, can not constitute an overload,
     so it can not add the constructor that only have a location parameter.*/
    public  User(String userName) {
        this.userName = userName;
    }

    public User(String userName, String location) {
        this.userName = userName;
        this.location = location;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public int getUserAge() {
        return userAge;
    }

    public void setUserAge(int userAge) {
        this.userAge = userAge;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public void testMethod () {
        System.out.println("hello!");
    }

    private void testWay () {
        System.out.println("overload");
    }

    public void testWay (int id) {
        System.out.println(id);
    }

    @Override
    public String toString() {
        /* Considering code writing from the bottom level, in order to cope with different functional requirements */
        return "User{" +
                "userName='" + this.getUserName()+ '\'' +
                ", userAge=" + this.getUserAge()+
                ", location='" + this.getLocation() + '\'' +
                '}';
    }
}

通过反射调用方法测试类:

public class GetMethodTest02 {

    public static void main(String[] args) {
        User user01 = new User();
        Class classObject01 = user01.getClass();

        Class classObject02 = User.class;

        Class classObject03 = null;
        try {
            classObject03 = Class.forName("com.bjsxt.demo.User");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        /* call the public method */
        Method method01 = null;
        try {
            method01 = classObject03.getDeclaredMethod("testWay",int.class);   // get designed method object.
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        Object user02 = null;
        try {
            user02 = classObject03.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        try {
            method01.invoke(user02,3);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        // how call the private method?

    }
}

老师,在调用方法的测试类中,如何调用自定义的用 private 修饰的 testWay() 方法?还是说通过反射只能调用类的 public 方法,不能调用 pirvate 的方法.

JAVA 全系列/第二阶段:JAVA 基础深化和提高/反射技术(旧) 16118楼
JAVA 全系列/第六阶段:项目管理与SSM框架/Mybatis 16119楼

ego_parent.zip

老师,是因为跨域的原因吗?image.png

JAVA 全系列/第十八阶段:亿级高并发电商项目_架构/编码(旧)/电商:使用SpringCache+Redis实现门户导航缓存 16120楼
Python 全系列/第十二阶段:Python_Django3框架/Django初级 16121楼
JAVA 全系列/第一阶段:JAVA 快速入门/控制语句、方法、递归算法 16122楼
Python 全系列/第十八阶段:数据分析-数据可视化/seaborn 16124楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637