解决can not access a member of class xxx with modifiers ““问题

本文分析了使用QueryRunner封装Bean时出现的访问权限问题,详细介绍了错误原因及解决办法,强调了Bean构造函数和类的公共访问权限的重要性。

项目场景:

在QueryRunner封装bean时出现

java.sql.SQLException: Cannot create backstage.bean.Estate: Class org.apache.commons.dbutils.BeanProcessor can not access a member of class backstage.bean.Estate with modifiers "" Query: select eid,`name`,introduction intro,pic,about from estate Parameters: []
	at org.apache.commons.dbutils.AbstractQueryRunner.rethrow(AbstractQueryRunner.java:392)
	at org.apache.commons.dbutils.QueryRunner.query(QueryRunner.java:351)
	at org.apache.commons.dbutils.QueryRunner.query(QueryRunner.java:212)
	at backstage.dao.BaseDao.getBeanList(BaseDao.java:103)
	at backstage.dao.impl.IEstateDaoImpl.getIndexEstate(IEstateDaoImpl.java:23)
	at test.EstateTest.testEstateDao(EstateTest.java:17)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:436)
	at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:170)
	at org.junit.jupiter.engine.execution.ThrowableCollector.execute(ThrowableCollector.java:40)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:166)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:113)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:58)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:112)
	at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:120)
	at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
	at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
	at java.util.Iterator.forEachRemaining(Iterator.java:116)
	at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
	at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
	at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
	at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
	at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
	at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
	at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:120)
	at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:120)
	at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
	at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
	at java.util.Iterator.forEachRemaining(Iterator.java:116)
	at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
	at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
	at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
	at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
	at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
	at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
	at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:120)
	at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:55)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:43)
	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:170)
	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:154)
	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:90)
	at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:86)
	at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)

问题描述:

困扰很久的问题
根据错误意思,问题是访问权限
项目结构
在这里插入图片描述
/WebTest/src/backstage/bean/Estate.java

package backstage.bean;

public class Estate {
	private Integer eid;
	private String name;
	private String intro;
	
	private String pic;
	private String about;
	
	Estate() {
		name = null;
		pic = "/WebTest/WebContent/img/index/hasiProject/kittens.jpg";
	}

	public Estate(Integer eid, String name, String intro, String pic, String about) {
		super();
		this.eid = eid;
		this.name = name;
		this.intro = intro;
		this.pic = pic;
		this.about = about;
	}

	public Integer getEid() {
		return eid;
	}

	public void setEid(Integer eid) {
		this.eid = eid;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getIntro() {
		return intro;
	}

	public void setIntro(String intro) {
		this.intro = intro;
	}

	public String getPic() {
		return pic;
	}

	public void setPic(String pic) {
		this.pic = pic;
	}

	public String getAbout() {
		return about;
	}

	public void setAbout(String about) {
		this.about = about;
	}

	@Override
	public String toString() {
		return "Estate [eid=" + eid + ", name=" + name + ", intro=" + intro + ", pic=" + pic + ", about=" + about + "]";
	}
	
}

/WebTest/src/backstage/dao/BaseDao.java

package backstage.dao;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import backstage.util.DBConnectUtil;



/**
 * 定义一个用来被继承的对数据库进行基本操作的Dao
 * 
 * @author YL
 *
 * @param <T>
 */
public class BaseDao<T> {
	private QueryRunner queryRunner = new QueryRunner();
	//定义一个变量来接收泛型的类型
	private Class<T> type;
	// 获取T的Class对象,获取泛型的类型,泛型是在被子类继承时才确定
	@SuppressWarnings("unchecked")
	public BaseDao() {
		//获取子类的类型
		@SuppressWarnings("rawtypes")
		Class clazz = this.getClass();
		//获取父类的类型
		//getGenericSuperclass()用来获取当前类的父类的类型
		//ParameterizedType表示的是带泛型的类型
		ParameterizedType parameterizedType = (ParameterizedType) clazz.getGenericSuperclass();
		//获取具体的泛型类型 getActualTypeArguments获取具体的泛型的类型
		//这个方法会返回一个Type的数组
		Type[] types = parameterizedType.getActualTypeArguments();
		//获取具体的泛型的类型·
		this.type = (Class<T>) types[0];
	}
	
	/**
	 * 通用的增删改操作
	 * 
	 * @param sql
	 * 		insert 
	 * 		delete
	 * 		update
	 * @param params
	 * @return
	 */
	public int update(String sql, Object... params) {
		// 获取连接
//		backstage.util.DBConnectUtil
		Connection connection = DBConnectUtil.getConn();
		int count = 0;
		try {
			count = queryRunner.update(connection, sql, params);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBConnectUtil.free(connection);
		}
		return count;
	}

	/**
	 * 获取一个对象
	 * 
	 * @param sql
	 * @param params
	 * @return
	 */
	public T getBean(String sql, Object... params) {
		// 获取连接
		Connection connection = DBConnectUtil.getConn();
		T t = null;
		try {
			t = queryRunner.query(connection, sql, new BeanHandler<T>(type),
					params);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBConnectUtil.free(connection);
		}
		return t;
	}

	/**
	 * 获取所有对象
	 * @param sql
	 * @param params
	 * @return
	 */
	public List<T> getBeanList(String sql, Object... params) {
		// 获取连接
		Connection connection = DBConnectUtil.getConn();
		List<T> list = null;
		try {
			list = queryRunner.query(connection, sql, new BeanListHandler<T>(type), params);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBConnectUtil.free(connection);
		}
		return list;
	}
	
}

/WebTest/src/backstage/dao/impl/IEstateDaoImpl.java

package backstage.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import backstage.bean.Estate;
import backstage.dao.BaseDao;
import backstage.dao.IEstateDao;
import backstage.util.DBConnectUtil;

public class IEstateDaoImpl extends BaseDao<Estate> implements IEstateDao {
//	private Connection conn = DBConnectUtil.getConn();

	@Override
	public List<Estate> getIndexEstate() {
		List<Estate> list = null;
		String sql = "select eid,`name`,introduction intro,pic,about from estate";
//		使用BaseDao解耦合
		list = this.getBeanList(sql);
//    	PreparedStatement pstmt = null;
//		try {
//			pstmt = conn.prepareStatement(sql);
//			ResultSet rs = pstmt.executeQuery();
//			list = new ArrayList<Estate>();
//			while(rs.next()) {
//				int eid = rs.getInt(1);
//				String name = rs.getNString(2);
//				String intro = rs.getNString(3);
//				String pic = rs.getNString(4);
//				String about = rs.getNString(5);
//				Estate estate = new Estate(eid,name,intro,pic,about);
//				list.add(estate);
//			}
//			pstmt.close();
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		return list;
	}
}

/WebTest/src/test/EstateTest.java 测试类

package test;

import java.util.List;

import org.junit.jupiter.api.Test;

import backstage.bean.Estate;
import backstage.dao.IEstateDao;
import backstage.dao.impl.IEstateDaoImpl;

class EstateTest {

	@Test
	void testEstateDao() {
//		fail("Not yet implemented");
		IEstateDao iEstateDao = new IEstateDaoImpl(); 
		List<Estate> list = iEstateDao.getIndexEstate();
		for (Estate estate : list) {
			System.out.println(estate);
		}
	}

}

原因分析:

bean的构造函数没有设置为public
导致QueryRunner无法创建

结论:

在使用QueryRunner封装bean时注意
使用QueryRunner数据库字段与bean字段不一致时sql要使用别名
注意bean的构造函数和类本身都要为public

package com.hw.camunda.utils; import com.hw.camunda.config.sensitive.SensitiveField; import java.lang.reflect.Field; import java.util.List; import java.util.Map; public class SensitiveUtils { public static void desensitize(Object obj) throws IllegalAccessException { if (obj == null) return; if (obj instanceof List<?>) { for (Object item : (List<?>) obj) { desensitize(item); } } else if (obj instanceof Map<?, ?>) { ((Map<?, Object>) obj).forEach((k, v) -> { try { desensitize(v); } catch (IllegalAccessException e) { e.printStackTrace(); } }); } else { Class<?> clazz = obj.getClass(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { //field.setAccessible(true); if (field.isAnnotationPresent(SensitiveField.class)) { Object value = field.get(obj); if (value instanceof String) { field.set(obj, desensitizeString((String) value)); } } else { Object nested = field.get(obj); if (nested != null && !isPrimitiveType(nested.getClass())) { desensitize(nested); } } } } } private static boolean isPrimitiveType(Class<?> clazz) { return clazz.isPrimitive() || clazz == String.class || Number.class.isAssignableFrom(clazz) || Boolean.class == clazz; } private static String desensitizeString(String str) { if (str == null || str.length() <= 4) return "*".repeat(Math.max(0, str.length())); return str.charAt(0) + "**" + str.charAt(str.length() - 1); } } Caused by: java.lang.IllegalAccessException: class com.hw.camunda.utils.SensitiveUtils cannot access a member of class com.hw.camunda.entity.SysUser with modifiers "private static final"
09-18
无法访问类 `com.ylzinfo.unemploy.domain.dto.CHSParamDTO` 成员的问题,可能由多种原因导致,以下是常见原因及对应的解决方案: ### 访问权限问题 如果成员被声明为 `private`,在类外部将无法直接访问。可以通过在类中提供 `public` 的访问方法(getter 和 setter)来解决。 ```java // 在 CHSParamDTO 类中 public class CHSParamDTO { private String someField; public String getSomeField() { return someField; } public void setSomeField(String someField) { this.someField = someField; } } // 在其他类中访问 public class OtherClass { public static void main(String[] args) { CHSParamDTO dto = new CHSParamDTO(); dto.setSomeField("value"); String value = dto.getSomeField(); } } ``` ### 类路径问题 确保类 `com.ylzinfo.unemploy.domain.dto.CHSParamDTO` 在当前项目的类路径中。如果是使用 IDE(如 IntelliJ IDEA 或 Eclipse),可以检查项目的依赖配置,确保相关的 JAR 包已正确添加。 ### 编译问题 如果代码有编译错误,可能会导致类或成员无法正常访问。检查项目的编译日志,解决所有编译错误。可以尝试重新编译项目,在命令行中使用 `javac` 命令: ```sh javac -cp your-classpath com/your/package/YourMainClass.java ``` ### 版本不兼容问题 如果使用的是第三方库中的类,确保库的版本与项目兼容。不同版本的库可能存在 API 差异,导致成员无法访问。 ### 反射访问问题 如果是通过反射访问类成员,确保反射代码正确。以下是一个反射访问成员的示例: ```java import java.lang.reflect.Field; public class ReflectionExample { public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException { CHSParamDTO dto = new CHSParamDTO(); Class<?> clazz = dto.getClass(); Field field = clazz.getDeclaredField("someField"); field.setAccessible(true); // 如果是 private 成员,需要设置可访问 field.set(dto, "value"); Object value = field.get(dto); System.out.println(value); } } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值